本文介绍了Java - 使用反射获取对静态类的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,是否可以使用反射访问静态类的实例(嵌套)?

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

假设我在包中定义了以下2个类 Package1.SubPackage.SubSubPackage:

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?

推荐答案

您是否尝试将嵌套类引用为

Have you tried referring to the nested class as

MyMainClass$SalesObjectGrouper1

嵌套类在内部命名ContainingClassName $ NestedClassName

Nested classes are internally named ContainingClassName$NestedClassName

这篇关于Java - 使用反射获取对静态类的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:28