相关疑难解决方法(0)

为什么内部类不能使用静态初始化器?

Quoth JLS#8.1.3:

内部类可能不会声明静态初始化器(第8.7节)......

这表现如下:

class A {
    class B {
        static { // Compile-time Error: Cannot define static initializer in inner type A.B
            System.out.println("Class is initializing...");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

既然Java的内部(非静态)类是由类加载器加载的,就像其他类一样,为什么我们不能为它们安装静态初始化器?

这种限制背后的原因是什么?

java inner-classes static-initializer jls

5
推荐指数
1
解决办法
2174
查看次数

如果使用getConstructor()的内部类,如何创建实例

可能重复:
Java:如何加载已经在类路径上的类(及其内部类)?

有人可以帮我理解如何使用getConstructor创建内部类的实例.

这就是我现在所处的位置.

import java.lang.reflect.*;

public class Outer{
public Outer(int i){
//things to do
}
public class Inner{
Class<?>[] type = new Class<?>[1];
Class<?> myClass;
    public Inner(int i){
    //stuff and code
    }

    public void task(){
    type[0] = Integer.class;
    try{
        myClass = Class.forName("Outer$Inner");
        Constructor construct = myClass.getConstructor(type);
        Object i = construct.newInstance(new Integer(43));
    }
    catch(Exception e){
        e.printStackTrace();
    }
    }
}

public static void main(String[] args){
Outer outer = new Outer(new Integer(21));
Inner inner = outer.new Inner(new Integer(22));
inner.task();
}
Run Code Online (Sandbox Code Playgroud)

}

错误信息 …

java reflection nosuchmethoderror getconstructor

3
推荐指数
1
解决办法
6460
查看次数