Reflection:
Gets the bytecode file object (Person.class) dynamically and runs on its members.
How to get a byte-code file object dynamically:
1: Any object is created by a bytecode file object, so any object can get its own bytecode file object
Then this function should be defined in object, so use GetClass ()
Need to first new object
2:每种数据类型都有一个 静态的class 属性,通过该属性可以得到字节码文件对象 不需要new对象,但是需要Person类存在 3:Class类提供了一个静态的forName(String str)方法 只需要提供字符串形式的包名+类名
1.Person Person1 = new Person ();//Load Person.class to method area class first<?extends Person>CLAZ1=Person1.GetClass();//Got A Person.class Person Person2=New Person();Class<?extends Person>CLAZ2=Person2.GetClass();//Got A Person.classSystem. out.println(CLAZ1==CLAZ2);//true----> Bytecode files are loaded only once to the method area, so the two get the same 2.Class< Person>CLAZ1= Person.class; 3.Class<?>CLAZ1 = Class.forName ("Com.reflect.Person");
gets the bytecode file object dynamically and creates the object:
1) Call the parameterless construction method to create the object
//when the non-parametric construction method does not exist, Occurs when the instantiationexception //occurs when the permissions of the constructor method are too low, illegalaccessexception public static void createobj1 () throws ClassNotFoundException, Instantiationexception, illegalaccessexception {//person person = new Person (); //get the Bytecode file object---person.class class<?> Claz = class.forname ( "Com.reflect.Person" ); //Use the Newinstance () method provided by class to create an object of type person Object obj = claz.newinstance (); //to create an object using an argument-free construction method Person person = (person) obj; System. out . println (person);}
2) Create an object using the constructor method with parameters
Public Static void CreateObj2() throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {//person person = new Person ("Little Red", +); //Get bytecode File object---person.classclass<?> Claz = Class.forName ("Com.reflect.Person");//Get the object of type constructor that the constructor method belongs toconstructor<?> Constructor = Claz.getconstructor (String.class,int. Class);//using construction methods to create objects--the ability to create objects with constructorPerson person = (person) constructor.newinstance ("Little Red", -); System. out. println (person);}
3) Dynamically create objects and assign values to attributes
class<?> Claz = Class. forname("Com.reflect.Person"); Gets the object of the field type to which the property name belongs//field field = Claz. GetField("Name");//can only get the property that the permission is publicSystem. out. println(field);//nosuchfieldexceptionField field = Claz. Getdeclaredfield("Name");Because name is a non-static property, it must be accessed through an object, so object obj = Claz is created first. newinstance();Set the Name property to an accessible field. Setaccessible(true);//The method is inherited from the parent classAssign a value to a property using the assignment function provided by the Field class field. Set(obj,"Little Red");System. out. println(obj);
4) Call the static method
publicstaticvoidmethod3() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //获取字节码文件对象---Person.class Class<?> claz = Class.forName("com.reflect.Person"); ///获取被调用的方法所属的 Method类型的对象 Method method = claz.getMethod("function"null); //执行方法 method.invoke(nullnull);}
5) Call the No-argument method through the object
Public Static void method1()throwsClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, IllegalAccessException, IllegalArgumentException, InvocationTargetException {//person person = new person ();p erson.show (); //Get bytecode File object---person.classclass<?> Claz = Class.forName ("Com.reflect.Person");//Gets the object of the method type to which the called Methods belongmethod = Claz.getmethod ("Show",NULL);//show () is non-static and requires the object to be calledObject obj = claz.newinstance ();//Execution MethodMethod.invoke (obj,NULL);}
6) Call the parameter method through an object
//Call a method with parameters Public Static void method2()throwsClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, IllegalAccessException, IllegalArgumentException, invocationtargetexception{//Get bytecode File object---person.classclass<?> Claz = Class.forName ("Com.reflect.Person");//Gets the object of the method type to which the called Methods belongmethod = Claz.getmethod ("Fun", String.class);//fun () is non-static and requires the object to be calledObject obj = claz.newinstance ();//Execution MethodMethod.invoke (obj,"Hello");}
Reflection Applications:
Here is a notebook, just beginning peripheral mouse. Later added keyboard, camera and so on.
Notebooks have running methods and use methods. Peripherals have open and close methods
publicclass NoteBook { publicvoidruning(){ System.out.println("电脑运行"); } publicvoiduseKeyBoard(KeyBoard kb){ if(kb!=null){ kb.open(); kb.close(); } newnew KeyBoard ();noteBook.use(keyBoard );
What if I add a peripheral mouse?
Notebook also has to add a usemouse (Mouse Mouse) {...} method, if you add peripherals again, you have to add the appropriate method.
Of course, here is easy to fix, define an excuse for USB.
interface Usb { publicvoidopen(); publicvoidclose();}
Then let the peripherals to implement this interface,
In notebook, we only use the definition of a
useUsb(Usb usb){ usb.open(); usb.close();}在主程里调用:Usb keyBoard = new KeyBoard ();noteBook.useUsb(keyBoard );Usb mouse = new Mouse();noteBook.useUsb(mouse);
If you want to add peripherals, just add the appropriate class and implement the USB interface, then the problem is that the main program has to new objects, call the same statement.
The solution can be reflected with:
1. Add all peripherals to a configuration file
Usb1=com.reflect.test.keyboard
Usb2=com.reflect.test.mouse
2. Calling in the main program
newnew FileInputStream("config\\config.properties");properties.load(fileInputStream); for(int i=1;i<=properties.size();i++){ String value properties.getProperty("usb"+i); ClassClass.forName(value); Object obj = claz.newInstance(); Usb usb = (Usb)obj; noteBook.useUsb(usb);}
–> Add peripherals are only added to the configuration file, and the main program calls are not modified
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Basic Notes-reflection and application