The title means:
Write a class by reflection, there is a method in the class. The method can set a property (construct method, member variable, member method) of a class to a specific value
Code:
1 The parameter list of the method is the class name of a class, the member variable, and the assigned value of the variable. 2 Public void setProperty (Object obj, String PropertyName, Object value) 3 throwsnosuchfieldexception, SecurityException,4 IllegalArgumentException, illegalaccessexception {5 6 // Gets the byte file object of the obj class 7Class C =Obj.getclass ();8 9 // Gets the member variable of the class TenField f =C.getdeclaredfield (PropertyName); One A // Cancel language access check -F.setaccessible (true); - the // Assign a value to a variable - f.set (obj, value); - -}
Test class:
1 Public Static voidMain (string[] args)throwsNosuchfieldexception,2 SecurityException, IllegalArgumentException, illegalaccessexception {3 4 //to create an object of the person class5Person p =NewPerson ();6 //Private member variables cannot be accessed directly7 //This is done directly by using the tool class that you just wrote.8Tool T =NewTool ();9 //change the private member variable directly by means of the tool nameTenT.setproperty (P, "name", "Zhang San"); One //change undefined type member variable AT.setproperty (P, "age", 13); - //change public member variables -T.setproperty (P, "sex", ' male '); the System.out.println (p); - - //In fact, in addition to the private member variable, the other can be assigned by the previous method - } + - } + A classPerson { at // The class has private member variables, undefined type member variables, public member variables - PrivateString name; - intAge ; - Public Charsex; - - @Override in PublicString toString () { - returnName + "--" + Sex + "--" +Age ; to } + -}
Java 27-8 reflection to set a property of an object to a specified value by reflection