package com.yusong.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestReflection
{
//能够打印传入的任何类的信息
public void printValue(Object obj) throws IllegalArgumentException, IllegalAccessException
{
Field [] field = obj.getClass().getDeclaredFields();
for(Field f:field)
{
f.setAccessible(true); //加了这句话,才能访问到私有的属性值
System.out.println(f);
System.out.println(f.getModifiers()+"<<"+f.getName()+"<<"+f.getType()+"<<"+f.get(obj));
if("name".equals(f.getName()))
{
f.set(obj, "kobe");
}
System.out.println(f.getModifiers()+"<<"+f.getName()+"<<"+f.getType()+"<<"+f.get(obj));
}
System.out.println("=========================================");
/*
//如果方法带有参数,invoke的时候就会抛异常,提示wrong number of arguments
//所以利用反射调用方法时一般不采用数组取得
Method [] methods = obj.getClass().getDeclaredMethods();
for(Method method:methods )
{
try
{
method.invoke(obj); //invoke()的时候会出错
}
catch (Exception e)
{
e.printStackTrace();
}
}
*/
try
{
Method m = obj.getClass().getDeclaredMethod("print", String.class);
//调用私有的方法
m.setAccessible(true);
m.invoke(obj, "yusong");
Method m1 = obj.getClass().getDeclaredMethod("print", String.class);
m1.setAccessible(true);
m1.invoke(obj, "songyu");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestReflection ref = new TestReflection();
User user = new User("james",25,"china");
try
{
ref.printValue(user);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class User
{
private String name ; //2
public int age; //1
private String loacation; //protected 4 ,不加就是0表示
public User(){};
public User(String name, int age, String loacation)
{
super();
this.name = name;
this.age = age;
this.loacation = loacation;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getLoacation()
{
return loacation;
}
public void setLoacation(String loacation)
{
this.loacation = loacation;
}
private void print(String name) //私有的方法
{
System.out.println("Hello World"+name);
}
}