如何在Java中加载嵌套类? [英] How to load nested classes in Java?

查看:120
本文介绍了如何在Java中加载嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下java代码:

I have the following java code:

public class CheckInnerStatic {

private static class Test {
    static {
        System.out.println("Static block initialized");
    }
    public Test () {
        System.out.println("Constructor called");
    }
}

    public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("Inside main");
        Class.forName("Test");    // Doesn't work, gives ClassNotFoundException
        //Test test = new Test();   // Works fine
    }
}

为什么不是 class.forName(Test)在下一行工作正常的时候在这里工作?

Why doesn't the class.forName("Test") work here while the next line works fine?

推荐答案

使用外部$嵌套(无论嵌套类是否为静态)

Use Outer$Nested (regardless if nested class is static or not)

public class CheckInnerStatic {

    private static class Test {
    static {
        System.out.println("Static block initialized");
    }
    public Test () {
        System.out.println("Constructor called");
    }
}

    public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println("Inside main");
        Class<?> cls = Class.forName("CheckInnerStatic$Test");
        //Test test = new Test();
    }
}

这篇关于如何在Java中加载嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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