Principle: Java reflection is able to get the name of a property and then invoke a method of the class by invoking it.
For example, there is a property called username, this class has written a method called GetUserName, Invoke call GetUserName this method.
The code is as follows
Copy Code code as follows:
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import Java.util.HashMap;
Import Java.util.Map;
public class Parameterbase
{
/**
* Get Class field and value Map
* @return
*/
Public map<string, string> GetClassInfo ()
{
map<string,string> fieldsandvalues = new hashmap<string, string> ();
Field [] fields = This.getclass (). Getdeclaredfields ();
for (int i=0; i< fields.length; i++)
{
Field f = fields[i];
String value = GetFieldValue (this, F.getname ()). ToString ();
Fieldsandvalues.put (F.getname (), value);
}
return fieldsandvalues;
}
private string GetFieldValue (Object owner, String fieldName)
{
Return InvokeMethod (owner, Fieldname,null). toString ();
}
/**
*
* GetField method to perform a field
*
* @param owner Class
* @param the property name of the FieldName class
* @param args parameter, default to NULL
* @return
*/
Private Object InvokeMethod (object owner, String fieldName, object[] args)
{
class<? Extends object> Ownerclass = Owner.getclass ();
FieldName-> FieldName
String methodname = fieldname.substring (0, 1). toUpperCase () + fieldname.substring (1);
Method method = null;
Try
{
method = Ownerclass.getmethod ("get" + methodname);
}
catch (SecurityException e)
{
E.printstacktrace ();
}
catch (Nosuchmethodexception e)
{
E.printstacktrace ();
Return "";
}
Invoke GetMethod
Try
{
Return Method.invoke (owner);
}
catch (Exception e)
{
Return "";
}
}
}
Write a class user inherits from Parameterbase and writes a test code
Copy Code code as follows:
public class User extends Parameterbase
{
String UserName;
String Passworld;
Public String GetUserName ()
{
return userName;
}
public void Setusername (String userName)
{
This.username = UserName;
}
Public String Getpassworld ()
{
return passworld;
}
public void Setpassworld (String passworld)
{
This.passworld = Passworld;
}
public static void Main (string[] args)
{
User U = new user ();
U.passworld = "123";
U.username = "AAAAA";
System.out.println (U.getclassinfo (). toString ());
}
}
Program Output
Copy Code code as follows:
{passworld=123, username=aaaaa}