Java利用反射访问私有构造函数的例子

2020-12-15 10:37:27 浏览数 (1)

参考链接: Java构造函数

import java.lang.reflect.Constructor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class Test {

    public static void main(String[] args) throws Exception {

        //get Constructor

        Class clazz = Class.forName("T");

        Constructor cons = clazz.getDeclaredConstructor(null);

        //set accessble to access private constructor

        cons.setAccessible(true);

        cons.newInstance(null);

    }

}

class T {

    private T() {

        System.out.println("init T");

    }

}

0 人点赞