package com.test;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class JavaTest {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static void main(String [] args){
JavaTest jTest = new JavaTest();
jTest.setName("madp");
jTest.setPassword("123");
Class classType = jTest.getClass();
try {
JavaTest jTest2 = (JavaTest)classType.getConstructor(new Class[]{}).newInstance(new JavaTest[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//获得对象所有的属性
Field fields[] = classType.getDeclaredFields();
for(int i=0;i<fields.length;i++){
Field field = fields[i];
String fieldName = field.getName();
//获得和属性对应的getXXX()方法的名字
String getMethodName = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
Method getMethod = null;
try {
//获得和属性对应的getXXX()方法
getMethod = classType.getMethod(getMethodName, new Class[]{});
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object value = null;
try {
//调用对象的getXXX()方法
value = getMethod.invoke(jTest, new JavaTest[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}