在Java中,是否可以使用反射来访问静态类(嵌套)的实例?
假设我在包 Package1.SubPackage.SubSubPackage中定义了以下2个类:
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");
}
}
如果我运行以下代码:
try {
xyz = Class.forName( "Package1.SubPackage.SubSubPackage.MyMainClass.SalesObjectGrouper1" );
} catch( ClassNotFoundException ex ) {
// always hit the error
}
将会出现错误,指示找不到类。能做到吗?
最佳答案
您是否尝试过将嵌套类引用为
MyMainClass$SalesObjectGrouper1
嵌套类在内部被命名为ContainingClassName $ NestedClassName