Java反射机制-学习笔记2(二)

2014-11-24 08:07:31 · 作者: · 浏览: 1
tMethod = objClass.getMethod(methodName);
System.out.println(getMethod.invoke(obj));

} catch (NoSuchMethodException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}

public static void setter(Object obj, String attr, Object value) {
try {
Class< > objClass = obj.getClass();
String methodName = "set" + attr.substring(0, 1).toUpperCase() + attr.substring(1);
Method setMethod = objClass.getMethod(methodName, value.getClass());
setMethod.invoke(obj,value);

} catch (NoSuchMethodException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
【结果:】

[html]
xiaozhang


【实例10】通过反射操作类的属性

[java]
public class ReflectTest {
public static void main(String[] args) {
Class< > personClass = null;

try {
personClass = Class.forName("org.zhang.test.Person");
Person person = (Person) personClass.newInstance();
person.setName("old name");
person.setSex("male");
System.out.println(person.getName());

Field nameField = personClass.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(person,"new name");
System.out.println(nameField.get(person));

} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (NoSuchFieldException e){
e.printStackTrace();
}

}
}
【结果:】

[html]
old name
new name

【实例11】通过反射,操作数组
[java]
public class ReflectTest {
public static void main(String[] args) {
int [] temp = {1,2,3,4,5};
Class< > tempClass = temp.getClass().getComponentType();
System.out.println("数组类型:" + tempClass.getName());
System.out.println("数组长度:" + Array.getLength(temp));
System.out.println("数组的第一个元素:" + Array.get(temp,0));
Array.set(temp,0,100);
System.out.println("修改后的第一个元素是:" + Array.get(temp,0));
}
}
【结果:】

[html]
数组类型:int
数组长度:5
数组的第一个元素:1
修改后的第一个元素是:100


【实例12】获取类加载器

[java]
public class ReflectTest {
public static void main(String[] args) {
Person p = new Person();
System.out.pri