簡體   English   中英

使用公共構造函數 Java 聲明一個私有 static 嵌套 class?

[英]Declare a private static nested class with a public constructor Java?

如何使用公共構造函數創建 static 私有內部 class 的實例?

public class outerClass<E> {
private static class innerClass<E> {
    E value;
    
    public innerClass(E e) {
        value = e;
    }
}}

我已經嘗試過了,它給出了一個錯誤,即 out package 不存在

outerClass<Integer> out = new outerClass<Integer>();
out.innerClass<Integer> = new out.innerClass<Integer>(1);

我已經嘗試過了,它給出了一個錯誤,即內部 class 是私有的並且無法訪問。

outerClass<Integer>.innerClass<Integer> = new 
outerClass<Integer>.innerClass<Integer>(1)

new out.innerClass<Integer>(1);

但這沒有意義。 innerClass聲明為static ,表示 innerClass 與outerClass 它只是出於命名空間的目的而位於其中(並且,也許外部和內部可以訪問private成員),但這就是它的終點。 所以, out ,作為outerClass的一個實例,沒有業務存在。

new outerClass<Integer>.innerClass<Integer>(1)

這也沒有任何意義 - 這里提到的外層類只是為了命名空間:告訴 java 你的意思是什么 class 。 因此,上面的<Integer>沒有意義。

那我該怎么做呢?

new outerClass.innerClass<Integer>(1);

你沒有提到約束,所以....

反思救援!

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM