Interview question: can the private constructor class be accessed externally? Reflection and question Structure
Brute-force cracking is accessible during reflection.
package com.swift.fanshe;import java.util.List;public class Fanshe { String name="swift"; private Fanshe(List list) { System.out.println("list"); }}
Call the above class using the Reflection Method
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, expiration, InvocationTargetException {Class clazz = Class. forName ("com. swift. fanshe. fanshe "); Constructor c = clazz. getDeclaredConstructor (List. class); c. setAccessible (true); // brute-force open private construct Fanshe fanshe = (Fanshe) c. newInstance (new ArrayList (); System. out. println (fanshe. name );}}
After the constructor is cracked, the private constructor can also be accessed. The constructor obtains the constructor through the getDeclaredConstructor () method.