Java - Get reference to a static class using reflection

大城市里の小女人 提交于 2020-01-13 08:36:10

问题


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?


回答1:


Have you tried referring to the nested class as

MyMainClass$SalesObjectGrouper1

Nested classes are internally named ContainingClassName$NestedClassName




回答2:


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.



来源:https://stackoverflow.com/questions/3357478/java-get-reference-to-a-static-class-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!