反射
反射机制就是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
反射的使用
反射创建对象
package com.westos.entities;
public class Product {
private int id;
private String name;
private double price;
public Product() {
}
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
private void a(){
System.out.println("aaa");
}
}
方式1
Class<?> c = Class.forName("com.westos.entities.Product");//得到类对象
Product o = (Product)c.newInstance();//创建新的实例对象
方式2
Class<?> p = Product.class;//类对象
Product product = (Product) p.newInstance();//创建新的实例对象
反射得到本类的方法,包括公有的和私有的
Class<?> c = Class.forName("com.westos.entities.Product");
Method[] methods = c.getDeclaredMethods();
for(Method method:methods)
System.out.println(method);
反射得到本类及继承的所有公有方法
Class<?> c = Class.forName("com.westos.entities.Product");
Method[] methods = c.getMethods();
for(Method method:methods)
System.out.println(method);
反射获取单个方发法
Class<?> c = Class.forName("com.westos.entities.Product");
Method setId = c.getMethod("setId",int.class);
System.out.println(setId);
反射调动方法
Class<?> c = Class.forName("com.westos.entities.Product");
Product p = (Product)c.newInstance();
Method a = c.getDeclaredMethod("a");
a.setAccessible(true);
System.out.println(a);
a.invoke(p);
通过反射得到本类的私有和公有属性
Field[] fields = c.getDeclaredFields();
反射调用有参构造
Class<Product> c = Product.class;
Constructor<Product> constructor = c.getConstructor(int.class, String.class, double.class);
Product aa = constructor.newInstance(1, "aa", 12.3);
System.out.println(aa);