Java USES reflection to get the class attribute value of the implementation code
- 2020-04-01 02:13:36
- OfStack
How it works: reflection in Java can get the name of the property and then invoke a method of the class.
For example, if you have a property called userName, and this class writes a method called getUserName, call the getUserName method by invoking.
The following code
Write a class User inherited from ParameterBase and write a test code
Program output
For example, if you have a property called userName, and this class writes a method called getUserName, call the getUserName method by invoking.
The following code
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ParameterBase
{
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();
}
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 inherited from ParameterBase and write a test code
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
{passWorld=123, userName=aaaaa}