Java - Get reference to a static class using refle

2019-04-24 08:30发布

In Java, is it possible to access an instance of a static class (nested) using reflection?

Supposing I have the following 2 classes defined in the package Package1.SubPackage.SubSubPackage:

public class MyMainClass {  
   public static class SalesObjectGrouper1 {  
      public static final GrouperContext CONTEXT = new GrouperContext("MyDate");  
   }  

   private static class SalesObjectGrouper2 {  
      public static final GrouperContext CONTEXT = new GrouperContext("MyDate");  
   }  
}  

If I run the following code:

try {
     xyz = Class.forName( "Package1.SubPackage.SubSubPackage.MyMainClass.SalesObjectGrouper1" );
} catch( ClassNotFoundException ex ) {
     // always hit the error
}

it will error indicating class cannot be found. Can this be done?

2条回答
孤傲高冷的网名
2楼-- · 2019-04-24 08:39

To avoid hacks in the mapping of Java language classes on to the Java runtime classes, you could use Class.getDeclaredClasses. Using reflection is often a mistake. Dealing with nested classes does not seem to be a good sign.

查看更多
时光不老,我们不散
3楼-- · 2019-04-24 08:56

Have you tried referring to the nested class as

MyMainClass$SalesObjectGrouper1

Nested classes are internally named ContainingClassName$NestedClassName

查看更多
登录 后发表回答