java 使用 Class.forName 实例化嵌套的静态类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7007831/
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
Instantiate nested static class using Class.forName
提问by ssedano
I have a nested static class
like:
我有一个nested static class
喜欢:
package a.b
public class TopClass {
public static class InnerClass {
}
}
I want to instantiate with Class.forName()
but it raises a ClassNotFoundException
.
我想实例化,Class.forName()
但它引发了一个ClassNotFoundException
.
Class.forName("a.b.TopClass"); // Works fine.
Class.forName("a.b.TopClass.InnerClass"); // raises exception
TopClass.InnerClass instance = new TopClass.InnerClass(); // works fine
What is wrong in my code?
我的代码有什么问题?
Udo.
你做。
回答by Jon Skeet
Nested classes use "$" as the separator:
嵌套类使用“$”作为分隔符:
Class.forName("a.b.TopClass$InnerClass");
That way the JRE can use dots to determine packages, without worrying about nested classes. You'll spot this if you look at the generated class file, which will be TopClass$InnerClass.class
.
这样 JRE 就可以使用点来确定包,而不必担心嵌套类。如果您查看生成的类文件,您会发现这一点,该文件将是TopClass$InnerClass.class
.
(EDIT: Apologies for the original inaccuracy. Head was stuck in .NET land until I thought about the filenames...)
(编辑:为最初的不准确道歉。在我想到文件名之前,头一直停留在 .NET 领域......)
回答by Silfverstrom
try
尝试
Class.forName("a.b.TopClass$InnerClass");
Class.forName("a.b.TopClass$InnerClass");
回答by Art Licis
Inner classes are accessed via dollar sign:
内部类通过美元符号访问:
Class.forName("a.b.TopClass");
Class.forName("a.b.TopClass$InnerClass");
回答by Sumit Jhajharia
Inner class is always accessed via dollar sign because when java compiler compile the java source code file it generates .class file(byte code).
内部类总是通过美元符号访问,因为当 java 编译器编译 java 源代码文件时,它会生成 .class 文件(字节码)。
if there is only one class for example Hello.java and this class is an outer class then java compiler on compilation generate Hello.class file but if this class has an inner class HelloInner then java compiler generates d Hello$HelloInner.class(byte code).
如果只有一个类,例如 Hello.java 并且这个类是一个外部类,那么编译时 java 编译器会生成 Hello.class 文件,但是如果这个类有一个内部类 HelloInner,那么 java 编译器会生成 d Hello$HelloInner.class(byte code )。
so bytecode always looks like for following snippet with name Outer.java:
所以字节码总是看起来像以下名称为 Outer.java 的片段:
public class Outer
{
public var;//member variable
Outer()//constructor
{
}
class Inner1
{
class Inner2
{
}
}
}
so byte code is:Outer$Inner1$Inner2.class
所以字节码是:Outer$Inner1$Inner2.class
that's why we use $ sign to access inner class .:)
这就是我们使用 $ 符号访问内部类的原因。:)