public static void main(String[] args) {
User user=new User();
user.setUsername ( "小王" );
user.setPhone ( "18526318888" );
user.setPassword ( "wang123" );
String password = user.getPassword ( );
System.out.println ( password );
System.out.println ( "======原始密码======" );
Class T =user.getClass ();
Field field = null;
//Field[] declaredField = T.getDeclaredFields();
System.out.println ( "=====输出所有属性名====" );
Field[] fields = T.getDeclaredFields();
for (Field f: fields) {
System.out.print(f.getGenericType().toString() + "\t");
//输出属性的名字
System.out.println(f.getName());
}
System.out.println ( "======利用反射修改密码======" );
try {
field = T.getDeclaredField ( "password" );
field.setAccessible ( true ); //忽略private属性
try {
//get方法:从user对象中取得field的值
System.out.println ( field.get ( user ) );
} catch (IllegalAccessException e) {
e.printStackTrace ( );
}
try {
//set方法第一个是对象,第二个参数是修改的值
field.set ( user,"wang666" );
} catch (IllegalAccessException e) {
e.printStackTrace ( );
}
try {
System.out.println ( field.get ( user ) );
System.out.println ( user );
} catch (IllegalAccessException e) {
e.printStackTrace ( );
}
} catch (NoSuchFieldException e) {
e.printStackTrace ( );
}
System.out.println ( "======利用反射获取构造方法======" );
Constructor[] constructors = T.getConstructors ( );
for (Constructor c: constructors) {
System.out.println ( c + "\t");
}
System.out.println ( "======利用反射获取方法======" );
Method[] methods = T.getMethods ( );
for (Method a: methods) {
System.out.println ( a + "\t");
}
}