java反射获取某接口的所有实现类

@SuppressWarnings("unchecked") private List> getAllSubclassOfTestInterface() {
        Field field = null;
        Vector v = null;
        List> allSubclass = new ArrayList>();
        Class scmJobClass = 
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class classOfClassLoader = classLoader.getClass();
        try {
            testInterfaceClass =
                    (Class) Class.forName("com.xxx.xxx.xxx.TestInterface");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "无法获取到TestInterface的Class对象!查看包名,路径是否正确");
         }
        while (classOfClassLoader != ClassLoader.class) {
            classOfClassLoader = classOfClassLoader.getSuperclass();
        }
        try {
            field = classOfClassLoader.getDeclaredField("classes");
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(
                    "无法获取到当前线程的类加载器的classes域!");
        }
        field.setAccessible(true);
        try {
            v = (Vector) field.get(classLoader);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(
                    "无法从类加载器中获取到类属性!");
        }
        for (int i = 0; i < v.size(); ++i) {
            Class c = (Class) v.get(i);
            if (scmJobClass.isAssignableFrom(c) && !scmJobClass.equals(c) && !abstractScmJobClass
                    .equals(c)) {
                allSubclass.add((Class) c);
            }
        }
        return allSubclass;
    }

获取到当前线程下的所有子类的类对象后,就可以neInstance,或者在bean中按照相应的命名规则查找到实例了。

你可能感兴趣的:(Java,java)