Yes, this is so cool,
Using the Java reflection mechanism, class can be used to get the variable field[] fields=cls.getdeclaredfields ();
You can also perform this method by using the name of the method in the class
M1 = Cls.getdeclaredmethod (Getmothodname (Fields[j].getname ()), string.class);
M1.invoke (Result,json.getstring (Fields[j].getname ()));
Use generics to get an example of this class T result= cls.newinstance (); the above can be executed
How the method name gets is assumed to say that a variable is named name so the parameter that sets this is setName ();
It is obvious that the variable name is preceded by a set and then the first character of the variable name is added together to SetName
The whole method is as follows:
public static <T> list<t> getObject (Jsonarray arr,class<t> cls) {field[] Fields=cls.getdeclar Edfields (); Method M1; list<t> list = new arraylist<t> (); try {T result = null;try {result = Cls.newinstance ()} catch (Instantiationexception e) {//TODO Auto-gene Rated catch Blocke.printstacktrace ();} for (int i=0;i<arr.length (); i++) {Jsonobject json = arr.getjsonobject (i); for (int j = 0; J < Fields.length; J + +) {m1 = Cls.getdeclaredmethod (Getmothodname (field S[j].getname ()), string.class); M1.invoke (Result,json.getstring (Fields[j].getname ())); } list.add (Result); }} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Nosuchmethodexception e) {/ /TODO auto-generated catch Blocke.printstacktrace ();} catch (Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IllegalarGumentexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (InvocationTargetException e) {//Todo A Uto-generated catch Blocke.printstacktrace ();} return list; } private static String Getmothodname (string name) {char[] b =name.tochararray (); if (b[0] >= && b[0] <= 122) {b[0] = (char) (B[0]-32); } string Mothodname= "Set" +new string (b); return mothodname; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fully automated parsing of JSON using Java reflection mechanism and generics