本帖最后由 一顿一只牛 于 2014-8-30 17:51 编辑
package com.itheima;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
/*
* 8、 定义一个标准的JavaBean,名叫Person,包含属性name、age。
* 使用反射的方式创建一个实例、调用构造函数初始化name、age,使用反射
* 方式调用setName方法对名称进行设置,不使用setAge方法直接使用反射方式对age赋值。
*
*
* */
public class Text8 {
/**
* @param args
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException, RuntimeException, NoSuchFieldException {
useReflect();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void useReflect() throws ClassNotFoundException, NoSuchMethodException, RuntimeException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException{
//获取Person类的字节码
Class clazz = Class.forName("com.itheima.Person");
//使用反射的方式创建一个实例、调用构造函数初始化name、age
Constructor<Person> con = (Constructor<Person>) clazz.getConstructor(String.class,int.class);
Person per = con.newInstance("zhangsan",24);
System.out.println("name:"+per.getName()+" "+"age:"+per.getAge());
//使用反射方式调用setName方法对名称进行设置
Method method = clazz.getMethod("setName", String.class);
method.invoke(per, "laowang");
System.out.println("调用setName方法对名称进行设置Name:"+per.getName());
//不使用setAge方法直接使用反射方式对age赋值,暴力获取字段。
Field field = clazz.getDeclaredField("age");
//允许反射私有方法
field.setAccessible(true);
//获取字段类型
Class type = field.getType();
if(type.equals(int.class)){
//设置字段值
field.set(per, 98);
//获取字段
int age = field.getInt(per);
System.out.println("直接使用暴力反射方式对字段age赋值:"+age);
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
出错
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at com.itheima.Text8.main(Text8.java:29)
|
|