Java中Reflect的基本使用

时间:2024-07-21 22:08:14

首先在package reflect下定义了一个类Book

 package reflect;

 class Book{
private String title;
private double price;
public Book() {
this("Java开发", 20.00);
}
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "标题: " + this.title + ", 价格:" + this.price;
}
}
 package reflect;

 import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays; public class Reflect {
public static void main(String[] args) throws Exception {
/**
* 通过Class.forName(String str)方法获取Class实例cls
* 通过getConstructor(parameterTypes)获取构造方法
* 通过get。。。获取 public的属性, 方法
* 通过getDeclared。。。获取public,protected, private属性, 方法
* 通过newInstance(parameterTypes)构造对象
*/
Class<?> cls = Class.forName("reflect.Book");
Constructor<?> con = cls.getConstructor(String.class, double.class);
Object obj = con.newInstance("你好", 2.5);
System.out.println(obj);
Method[] methods = cls.getDeclaredMethods();
// System.out.println(Arrays.toString(methods));
Method setTitle = cls.getMethod("setTitle", String.class);
Method getTitle = cls.getMethod("getTitle");
// 通过invoke(obj, paramter)执行获取的方法
setTitle.invoke(obj, "我好!");
System.out.println(getTitle.invoke(obj));
System.out.println(obj);
}
}