Thursday, 16 June 2016

[Java] How to get Inherited or same class in ClassLoader (클래스로더에 로드된 클래스 중 특정 클래스나 그 클래스를 상속받는 클래스 찾기)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class DorbaeClassLoaderUtil {
         public static java.util.List< Class< ?>> findInheritedClasses( ClassLoader classLoader, Class< ?> parentClass) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
  java.util.List< Class< ?>> filteredClasses = new java.util.LinkedList< Class< ?>>();
  
  Field f = ClassLoader.class.getDeclaredField( "classes");
  f.setAccessible( true);

  Vector< Class< ?>> classes = ( Vector< Class< ?>>)f.get( classLoader);
  int size = classes.size();
  Class< ?> cls = null;
  for ( int ll = 0; ll < size; ll++) {
    try {
     cls = classes.get( ll);
                 if ( parentClass.isAssignableFrom( cls)) {
                  filteredClasses.add( cls);
                 }
             
             } catch ( Exception e) {
              continue;

             } catch ( Error e) {
              continue;
              
             }
  }
  
  return filteredClasses;

 }
 
 public static void main( String[] args) throws Exception {
  A a = new A();
  B b = new B();
  C c = new C();
  
  System.out.println( "=================== All Classes ===================");
  java.util.Vector< Class< ?>> clss = DorbaeClassLoaderUtil.getAllLoadedClasses( Thread.currentThread().getContextClassLoader());
  for ( int ll = 0; ll < clss.size(); ll++) {
   System.out.println( clss.get( ll).getName());
   
  }
  
  System.out.println( "=================== Inherited Classes ===================");
  java.util.List< Class< ?>> clsss = DorbaeClassLoaderUtil.findInheritedClasses( Thread.currentThread().getContextClassLoader(), C.class);
  for ( int ll = 0; ll < clsss.size(); ll++) {
   System.out.println( clsss.get( ll).getName());
   
  }
 }

}

class A extends C {
 public A() {}
}

class B {
 public B() {}
 
}

class C {
 public C() {}
}


No comments:

Post a Comment