Java development for a long time, but has not been detailed understanding of the Java reflection mechanism, and later wrote the project found to use reflection can write a lot less boring code, so the simple implementation of Java reflection injection.
The specifics of the Java reflection can be found in this blog, written in very detailed, click here to enter ~
In general, business-based programming uses reflection implementations to inject attributes dynamically into an object.
Here is the method implementation:
1 /**2 * Instantiate an object by reflection based on the incoming map and class name3 * @paramClassName the class name that needs to be instantiated4 * @parammap contains the property's key-value pairs (string,object)5 * @returninstantiating a successful object6 */7 Public StaticObject Map2bean (String classname,map<string,object>map) {8Object obj=NULL;9 Try {Ten //instantiating an object based on a class name Oneobj=Class.forName (className). newinstance (); A - for(String key:map.keySet ()) { - if(key!=NULL&&! "". Equals (Key) { the - //capitalize the first character of a property -Character C=key.charat (0); -C=Character.touppercase (c); +String temp=string.valueof (c); - if(Key.length () >1) +Temp+=key.substring (1); A atMethod methods[]=Obj.getclass (). GetMethods (); - for(inti=0;i<methods.length;++i) { - //determine if the method name matches - if(Methods[i].getname (). Contains ("Set" +temp)) - { - //Execute method, pass in value in methods[i].invoke (obj, Map.get (key)); - Break; to } + } - } the } * //Method Method=obj.getclass (). GetMethod ("toString"); $ //method.invoke (obj, null);Panax Notoginseng}Catch(instantiationexception e) { - the e.printstacktrace (); +}Catch(illegalaccessexception e) { A the e.printstacktrace (); +}Catch(SecurityException e) { - $ e.printstacktrace (); $}Catch(IllegalArgumentException e) { - - e.printstacktrace (); the}Catch(InvocationTargetException e) { - Wuyi e.printstacktrace (); the}Catch(ClassNotFoundException e) { - Wu e.printstacktrace (); - } About returnobj; $ -}
Next is Call ~
Public Static voidMain (string[] args) {//Incoming ParametersMap<string,object> map=NewHashmap<string, object>(); Map.put ("id", 1); Map.put ("Name", "LZ"); Map.put ("Age", 20); Map.put ("Email", "[email protected]"); Map.put ("QQ", "100000"); Map.put ("Address", "TJ"); Person Person= (person) map2bean (person).class. GetName (), map); Person.tostring (); }
Java Reflection Simple Implementation injection