首页 > 代码库 > java反射(基础了解)
java反射(基础了解)
package cn.itcast_01;
/**
*Person类
*/
public class Person {
/** 姓名 */
private String name;
/** 年龄 */
private int age;
/** 性别 */
private String sex;
public Person(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
/**
* 无参数 show()方法
*/
public void show() {
System.out.println("你好");
}
/**
* 带参数 method()方法
*
*/
public void show(String id) {
System.out.println(id);
}
}
package cn.itcast_01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* java反射机制
*
* @author Petter
* @version 1.0
*
*/
public class Demo1 {
public static void main(String[] args) throws Exception {
//1.获取class字节码文件对象,即Person.class文件对象,即Class类对象
Class<?> c = Class.forName("cn.itcast_01.Person");
//2.1 通过构造器,获取任意单个空参构造方法
Constructor<?> con = c.getDeclaredConstructor();
//2.2 通过构造器,获取任意单个带参构造方法
Constructor<?> con1 = c.getDeclaredConstructor(String.class,int.class,String.class);
//3.1 通过构造对象创建Person实例
Object obj = con.newInstance();
System.out.println(obj); //Person [name=null, age=0, sex=null]
//3.2 通过构造对象创建Person实例
Object obj1 = con1.newInstance("小林",23,"女");
System.out.println(obj1); //Person [name=林青霞, age=23, sex=女]
//4. 获取私有成员变量并赋值
Field nameField = c.getDeclaredField("name");
Field ageField = c.getDeclaredField("age");
Field sexField = c.getDeclaredField("sex");
//暴力访问
nameField.setAccessible(true); //取消java语言的检查访问
ageField.setAccessible(true);
sexField.setAccessible(true);
//赋值
nameField.set(obj, "小猴");
ageField.set(obj, 23);
sexField.set(obj, "男");
System.out.println(obj); //Person [name=小猴, age=23, sex=男]
//5. 获取任意单个方法并使用
//无参数
Method m = c.getDeclaredMethod("show");
m.invoke(obj); //你好
//有参数
Method m1 = c.getDeclaredMethod("show", String.class);
m1.invoke(obj, "YY123"); //YY123
}
}
java反射(基础了解)