Java - 使用反射获取对静态类的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3357478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:28:17  来源:igfitidea点击:

Java - Get reference to a static class using reflection

javareflectionclassstatic

提问by Andez

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

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

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

假设我在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");  
   }  
}  

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?

它将错误指示找不到类。这能做到吗?

回答by Jim Garrison

Have you tried referring to the nested class as

您是否尝试将嵌套类称为

MyMainClass$SalesObjectGrouper1

Nested classes are internally named ContainingClassName$NestedClassName

嵌套类在内部命名为 ContainingClassName$NestedClassName

回答by Tom Hawtin - tackline

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.

为了避免在 Java 语言类到 Java 运行时类的映射过程中出现问题,您可以使用Class.getDeclaredClasses. 使用反射通常是错误的。处理嵌套类似乎不是一个好兆头。