反射常用API
1.Field类
package com.hspedu;
import java.lang.reflect.Field;
/**
* @author 韩顺平
* @version 1.0
*/
public class Car {
public String brand = "宝马";//品牌
public int price = 500000;
public String color = "白色";
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
", color='" + color + '\'' +
'}';
}
}
class v{
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
Class<Car> carClass = Car.class;
Car car = carClass.newInstance();
Field field = carClass.getField("brand");
Field field2 = carClass.getField("price");
//getType();以Class的形式返回类型
Class<?> type = field.getType();
System.out.println(type);//class java.lang.String,只是返回数据类型
Class<?> type1 = field2.getType();
System.out.println(type1);//int
//返回属性名getName()
String name = field.getName();
System.out.println(field.getName());//brand
//getModifiers();以数字形式返回属性的修饰符
int modifiers = field.getModifiers();
System.out.println(modifiers);//1
// toString();返回属性的总体情况:public String brand
// public java.lang.String com.hspedu.Car.brand
//getType();只是返回数据类型
System.out.println(field2.toString());//public int com.hspedu.Car.price
//get(car);返回属性的值,需要传入参数对象,注意区分返回属性名getName()
Object o2 = field.get(car);
System.out.println(o2);//宝马
Object o1 = field2.get(car);
System.out.println(o1.getClass());//class java.lang.Integer
}
}
import org.junit.Test;
import org.omg.CORBA.PERSIST_STORE;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect