How can I retrieve all classes that implement a cu

2019-09-24 10:32发布

问题:

I want to get all classes that implement the IFeature Interface. Java Refelctions appear to be a possible solution, but it doesn't work the way I want it to.

IFeature feature = new Landing();
Class<?>[] cls = Character.class.getInterfaces();
for(Class<?> c : cls ){
    System.out.println(c.toString());
}

the output

run:

interface java.io.Serializable

interface java.lang.Comparable

BUILD SUCCESSFUL (total time: 0 seconds)

my interface...

public interface IFeature {
    public abstract void update(HashMap<QueueIdentifier, Queue<Measurement>> messageMap);
    public abstract List<QueueIdentifier> getQIdList();
    public abstract int getCountSamples();
}

回答1:

The soluton is the ClassPathLoader from the apache atn library. Here my code...

ClassPathLoader cpl = new ClassPathLoader(".");
    try {
    Hashtable ht = cpl.getClasses();
    Set s = ht.keySet();
    Iterator iter = s.iterator();
    String fullName = null;
        while(iter.hasNext()) {
            try {
            fullName = (String) iter.next();
            Class cls = Class.forName(fullName);
            Class[] interfaces = cls.getInterfaces();
            for(int i = 0; i < interfaces.length; i++) {
            if(interfaces[i].getName().equals("IMyObserver.IFeature")) {

            Object o = cls.newInstance();
            }
        }