[英]Declare a private static nested class with a public constructor Java?
How do I create an instance of a static private inner class with a public constructor?如何使用公共构造函数创建 static 私有内部 class 的实例?
public class outerClass<E> {
private static class innerClass<E> {
E value;
public innerClass(E e) {
value = e;
}
}}
I've tried this and it gives an error that the out package does not exist我已经尝试过了,它给出了一个错误,即 out package 不存在
outerClass<Integer> out = new outerClass<Integer>();
out.innerClass<Integer> = new out.innerClass<Integer>(1);
I've tried this and it gives an error that the inner class is private and can't be accessed.我已经尝试过了,它给出了一个错误,即内部 class 是私有的并且无法访问。
outerClass<Integer>.innerClass<Integer> = new
outerClass<Integer>.innerClass<Integer>(1)
new out.innerClass<Integer>(1);
But this doesn't make sense.但这没有意义。
innerClass
is declared static
, which means that innerClass has nothing to do with outerClass
; innerClass
声明为static
,表示 innerClass 与outerClass
; it is merely located within it for namespacing purposes (and, perhaps, that outer and inner can access private
members), but that is where it ends.它只是出于命名空间的目的而位于其中(并且,也许外部和内部可以访问
private
成员),但这就是它的终点。 So, out
, being an instance of outerClass
, has no business being there.所以,
out
,作为outerClass
的一个实例,没有业务存在。
new outerClass<Integer>.innerClass<Integer>(1)
That also doesn't make any sense - outerClass is being mentioned here just for the purposes of namespacing: To tell java what class you mean.这也没有任何意义 - 这里提到的外层类只是为了命名空间:告诉 java 你的意思是什么 class 。 Thus, the
<Integer>
on that makes no sense.因此,上面的
<Integer>
没有意义。
new outerClass.innerClass<Integer>(1);
You didn't mention an constraints, so....你没有提到约束,所以....
package com.example;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ReflectionTest {
public static class OuterClass<E> {
private static class InnerClass<E> {
E value;
public InnerClass(E e) {
value = e;
}
}
}
@Test
public void should_instantiate_private_static_inner_class_w_reflection()
throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException,
IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> innerCls = Class.forName("com.example.ReflectionTest$OuterClass$InnerClass");
Constructor<?> ctor = innerCls.getConstructor(Object.class);
Object instance = ctor.newInstance(10);
Field valueField = innerCls.getDeclaredField("value");
valueField.setAccessible(true);
Object value = valueField.get(instance);
assertEquals(value, 10);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.