用Java反射实例化私有内部类

是否可以使用Java反射从另一个类实例化私有内部类。例如,如果我采用了这段代码

public class Main {

public static void main(String[] args) {}

}

class OtherClass {

private class Test {}

}

是否可以实例化并从main类中的main方法获得对Test的访问。

回答:

使用反射时,您会发现该内部类的构造函数将外部类的实例作为附加参数(总是第一个)。

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

public class OuterClass {

private class InnerClass {

}

public OuterClass() {

super();

}

public static void main(String[] args) {

// instantiate outer class

OuterClass outer = new OuterClass();

// List all available constructors.

// We must use the method getDeclaredConstructors() instead

// of getConstructors() to get also private constructors.

for (Constructor<?> ctor : OuterClass.InnerClass.class

.getDeclaredConstructors()) {

System.out.println(ctor);

}

try {

// Try to get the constructor with the expected signature.

Constructor<InnerClass> ctor = OuterClass.InnerClass.class

.getDeclaredConstructor(OuterClass.class);

// This forces the security manager to allow a call

ctor.setAccessible(true);

// the call

try {

OuterClass.InnerClass inner = ctor.newInstance(outer);

System.out.println(inner);

} catch (InstantiationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

以上是 用Java反射实例化私有内部类 的全部内容, 来源链接: utcz.com/qa/399288.html

回到顶部