使用Class.forName实例化嵌套的静态类 [英] Instantiate nested static class using Class.forName

查看:533
本文介绍了使用Class.forName实例化嵌套的静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有嵌套静态类喜欢:

package a.b
public class TopClass {

    public static class InnerClass {
    }
}

我想用 Class.forName()进行实例化,但它会引发 ClassNotFoundException

I want to instantiate with Class.forName() but it raises a ClassNotFoundException .

Class.forName("a.b.TopClass"); // Works fine.
Class.forName("a.b.TopClass.InnerClass"); // raises exception

TopClass.InnerClass instance = new TopClass.InnerClass(); // works fine

我的代码有什么问题?

Udo。

推荐答案

嵌套类使用$作为分隔符:

Nested classes use "$" as the separator:

Class.forName("a.b.TopClass$InnerClass");

这样JRE可以使用点来确定包,而不必担心嵌套类。如果你看一下生成的类文件,你会发现这个,它将是 TopClass $ InnerClass.class

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.

(编辑:对原始的不准确性表示歉意。头部被困在.NET中,直到我想到文件名......)

( Apologies for the original inaccuracy. Head was stuck in .NET land until I thought about the filenames...)

这篇关于使用Class.forName实例化嵌套的静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆