/** Reflection gets private construction method run * Not recommended, corrupted program security, encapsulation * Violent private*/ Public classReflectDemo4 { Public Static voidMain (string[] args)throwsException {Class C=class.forname ("demo01. Person "); Constructor Con=c.getdeclaredconstructor (int.class, String.class); //constructor class, parent class AccessibleObject, defining Method Setaccessibile (Boolean flag)Con.setaccessible (true); Object obj=con.newinstance ("Lisi")); System.out.println (obj); }}
Packagedemo02;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;/** Defines the collection class, the generic string * requires adding an integer type * reflection to the collection, gets the class file object of the collection ArrayList classes * Through the class file object, call the Add method * * To understand whether the reflection call method*/ Public classReflecttest { Public Static voidMain (string[] args)throwsException {ArrayList<String> array=NewArraylist<>(); Array.add (A); //reflection mode, gets the class file object of the collection ArrayListClass c=Array.getclass (); //get the method in the Arraylist.class file addMethod Method=c.getmethod ("Add", Object.class); System.out.println (method); //To run the ArrayList method using invoke AddMethod.invoke (array,150); Method.invoke (Array,1500); Method.invoke (Array,15000); SYSTEM.OUT.PRINTLN (array); //the enhanced for loop cannot traverse, }}
Java uses reflection to get private construction methods, and reflection erase generic data type constraints