面试题:私有构造方法类外部能访问吗,用什么方法?反射
反射的时候通过暴力破解是可以访问的
package com.swift.fanshe; import java.util.List; public class Fanshe { String name="swift"; private Fanshe(List list) { System.out.println("list"); } }
用反射的方法调用上面的类
package com.swift.fanshe; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class TestFanshe { @Test public void test() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clazz=Class.forName("com.swift.fanshe.Fanshe"); Constructor c=clazz.getDeclaredConstructor(List.class); c.setAccessible(true);//暴力打开私有构造 Fanshe fanshe=(Fanshe) c.newInstance(new ArrayList()); System.out.println(fanshe.name); } }
对构造器进行暴力破解后,私有的构造也可以访问,这个构造器的获得要通过getDeclaredConstructor()方法
Never waste time any more, Never old man be a yong man