package com.ld.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;
public class App {
private static Person person1;
static {
person1 = new Person("liudong", "12");
}
static Person person = person1;
public static void main(String[] args) throws Exception {
byMethodCreateObj();
}
// 对属性进行操作
public static void doField() throws Exception {
Class classType = Person.class;
Field f1 = classType.getDeclaredField("name");
Field f2 = classType.getDeclaredField("sex");
f1.setAccessible(true);
f2.setAccessible(true);
f1.set(person, "刘东4");
f2.set(person, "男");
System.out.println(person.getName() + " " + person.getSex());
}
public static void byMethodCreateObj() throws Exception {
Class classType = Person.class;
// 调用方法
Method method = classType.getMethod("setName", String.class);
method.invoke(person, "刘东3");
System.out.println(person.getName());
// 调用私有方法
Method m2 = classType.getDeclaredMethod("say");
m2.setAccessible(true);
m2.invoke(person);
}
public void byConCreateObj() throws Exception {
@SuppressWarnings("rawtypes")
Class classType = (person.getClass());
@SuppressWarnings({ "unchecked", "rawtypes" })
Constructor c = classType.getConstructor(String.class, String.class);
Object obj = c.newInstance("刘东", "14");
System.out.println("通过构造方法创建的obj是不是Person类" + (obj instanceof Person));
System.out.println(((Person) obj).getName());
}
public static void bySetCreateObj() throws ClassNotFoundException,
NoSuchMethodException {
// 返回与带有指定字符串的类或接口相关联的Class对象;
// Class classtype = Person.class;
// Class classType = person.getClass();
Class classType = Class.forName("com.ld.reflect.App$Person");
Object obj = classType.getConstructor();
System.out.println("使用反射机制创建狐臭俩的对象是否是Person对象"
+ (obj instanceof Person));
}
static class Person {
private static String name = "刘东";
private static String sex = "nam";
public Person() {
super();
}
public Person(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
private static void say() {
System.out.println("My name is" + name);
}
}
}
java反射机制生成对象
最新推荐文章于 2022-05-11 09:45:17 发布