Java:how to find the class with the interface implemented

Asked 1 years ago, Updated 1 years ago, 35 views

I want to get a class using interface

public interface IExtension {
    String getName();

    String getVersion();
  }

  public class AExtension implements IExtension {

    @ Override
    public String getName() {
      return "A";
    }

    @ Override
    public String getVersion() {
      return "1.0.0";
    }
  }

  public class BExtension implements IExtension {

    @ Override
    public String getName() {
      return "B";
    }

    @ Override
    public String getVersion() {
      return "1.0.0";
    }
  }

java

2022-09-30 21:32

2 Answers

When running Java, there is a way to retrieve it using the getSubTypesOf method in reflections.

package com.detect.subclasses;

import org.reflections.Reflections;
import org.testng.annotations.Test;

import java.util.Set;

publicclassDetectSubClassesTest{

    @ Test
    public void getSubclasses() {
        Set<Class<?extends IExtension>>subTypes=
                new Reflections("com.detect.subclasses").getSubTypesOf(IExtension.class);

        assert subTypes.size()==2;

        subTypes.forEach(System.out:println);
    }

    public interface IExtension {
        String getName();

        String getVersion();
    }

    public static class AExtension implements IExtension {

        @ Override
        public String getName() {
            return "A";
        }

        @ Override
        public String getVersion() {
            return "1.0.0";
        }
    }

    public static class BExtension implements IExtension {

        @ Override
        public String getName() {
            return "B";
        }

        @ Override
        public String getVersion() {
            return "1.0.0";
        }
    }
}

Result:

class com.detect.subclasses.detectSubClassesTest$AExtension
class com.detect.subclasses.DetectSubClassesTest$BExtension


2022-09-30 21:32

You can grep the source directory with the implementations IE Extension keyword or use IDE's search function (such as Type Hierarchy).


2022-09-30 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.