読者です 読者をやめる 読者になる 読者になる

先祖クラスのコンストラクタでインスタンスを生成する方法

先祖クラスのコンストラクタインスタンスを生成するサンプルプログラム

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ConstructorForSerializationExample {
    public static void main (String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Constructor cons = ConstructorForSerializationFactory.newConstructorForSerialization (Child.class, Parent.class);

        Child child = (Child)cons.newInstance ();
        System.out.println ("child.name = " + child.name);

        Field field = Child.class.getDeclaredField ("name");
        field.setAccessible (true);
        field.set (child, "Vakabon");
        System.out.println ("child.name = " + child.name);
    }

    public static class Parent {
    }

    public static class Child extends Parent {
        private final String name;

        public Child (String name) {
            this.name = name;
        }
    }
}

先祖クラスのコンストラクタインスタンスを生成する部分

import sun.reflect.ReflectionFactory;

import java.lang.reflect.Constructor;
import java.security.AccessController;

public class ConstructorForSerializationFactory {
    private static final ReflectionFactory reflFactory = (ReflectionFactory)AccessController.doPrivileged (new ReflectionFactory.GetReflectionFactoryAction ());

    public static Constructor newConstructorForSerialization (Class<?> classToBeInstantiated, Class<?> targetAncestorClass, Class<?>... paramTypes) throws NoSuchMethodException {
        return reflFactory.newConstructorForSerialization (classToBeInstantiated, targetAncestorClass.getDeclaredConstructor (paramTypes));
    }
}