反射基础知识应用
1、从类对象内获取基本信息
类的信息一般在动态实例化时会用到,或者重新设置值、修改等。
public class TestReflect {
public static void main(String[] args) throws Exception{
//类获取
Class myClass = Product.class;
String className = myClass.getCanonicalName() ;//在运行期获取的类名字符串
System.out.println("类全名:"+className);
//同样类的各种信息均可从类对象内获取
Class objClass = Class.forName(className);
// 取构造函数
Constructor[] constructors = objClass.getConstructors();
for(Constructor con : constructors){
System.out.println("构造方法名 = " + con.getName());
}
// 取字段
Field[] fields = objClass.getDeclaredFields();
for(Field field : fields){
System.out.println("字段 = " + field.getName());
}
//取修饰符
int modifiers = fields[0].getModifiers();
System.out.println("修饰符数字 = " + modifiers);
System.out.println("修饰符 = " + Modifier.isPrivate(modifiers));
//获取类方法,这里也会打印父类(object)方法
Method[] methods = objClass.getMethods();
for(Method method : methods){
System.out.println("方法 = " + method.getName());
}
}
}
设置一个类,主要配合前后代码使用
public class Product {
private String id;
private String name;
public String code;
public Product(String id, String name) {
super();
this.id = id;
this.name = name;
this.code = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// public String getCode() {
// return code;
// }
// public void setCode(String code) {
// this.code = code;
// }
}
2、类实例化
知道一个类及其构造参数,可以进行实例化
public class TestInstance {
public static void main(String[] args) throws Exception{
//利用构造实例化类
Constructor constructor = Product.class.getConstructor(String.class,String.class);
Product prod = (Product)constructor.newInstance("1001","name-测试");
System.out.println("产品名:"+prod.getName());
Class aClass = Product.class;
Field field = aClass.getDeclaredField("code");
Product instance = new Product("1001","产品名");
Object value = field.get(instance);
//如果对象内这个字段存储有值这里将显示相应值
System.out.println("value="+value);
field.set(instance, value);
System.out.println("field="+field.getName());
}
}
3、注解反射
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})//设置目标位置
public @interface Handler {
String name();
String value();
}
@Handler(name="bussiness" , value ="Hello class" )
public class HandlerClass {
protected List<String> stringList = new ArrayList<>();
@Handler(name="methodName", value = "Hello method" )
public void doMethod(){
}
public List<String> getStringList(){
return this.stringList;
}
}
注解的获取
public class TestAnnotation {
public static void main(String[] args) {
//这里只介绍怎么获取注释
Class aClass = HandlerClass.class ;
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation : annotations){
if (annotation instanceof Handler){
Handler anno = (Handler) annotation;
System.out.println("name: " + anno.name());
System.out.println("value: " + anno.value());
}
}
//取方法注释
Annotation[] methods = aClass.getMethods()[0].getDeclaredAnnotations();
//Annotation annotation = aClass.getAnnotation(Handler.class);
for (Annotation annotation : methods){
if (annotation instanceof Handler){
Handler ann = (Handler) annotation;
System.out.println("name: " + ann.name());
System.out.println("value: " + ann.value());
}
}
}
}
4、泛型
从一个方法中判断返回类型的泛型
public class TestGeneric {
public static void main(String[] args) throws Exception {
//这里主要测试方法的返回类型的泛型
Method method = HandlerClass.class.getMethod("getStringList",null);
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
for (Type typeArgument : typeArguments){
Class typeArgClass = (Class) typeArgument;
System.out.println("typeArgClass = " + typeArgClass);
}
}
}
}
5、数组
从数组实例到数据设置
public class TestArray {
public static void main(String[] args) throws Exception{
//创建数组
int [] intArray = (int []) Array.newInstance(int.class , 3);
intArray[0] = 4;
Array.set(intArray, 1, 456 );//反射设值
System.out.println("长度:"+intArray.length);
for (int i=0;i<intArray.length ;i++) {
System.out.println("位置"+i+"="+intArray[i]);
}
//反射取值
System.out.println("intArray[0] = " + Array.get(intArray, 0));
//这里利用了jvm编译后概念
Class intCla = Class.forName("[I");
System.out.println("类型:"+intCla.getSimpleName());
System.out.println("是数组吗: " + intCla.isArray());
}
}
6、动态代理
对方法进行动态代理,在方法执行前后进行置入
public class TestProxy {
public static void main(String[] args) {
//测试动态代理
ProxyClass targetObject = new ProxyClass();
XProxyHandler handler = new XProxyHandler(targetObject);
//生成代理对象
ProxyInterface object = (ProxyInterface) Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
targetObject.getClass().getInterfaces(), handler);
//调用
String ret = object.method("test");
System.out.println("结果: " + ret);
}
}
//目标类接口
interface ProxyInterface {
String method(String buss);
}
//目标类
class ProxyClass implements ProxyInterface{
public String method(String buss){
System.out.println("执行业务方法进行中");
return "return-"+buss;
}
}
//代理操作
class XProxyHandler implements InvocationHandler {
//代理类中的真实对象
private Object targetObj;
//构造函数,给我们的真实对象赋值
public XProxyHandler(Object targetObj) {
this.targetObj = targetObj;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("调用方法之前..........");
Object invoke = method.invoke(targetObj, args);
System.out.println("调用方法之后..........");
return invoke;
}
}
7、类加载
public class TestClassLoader {
public static void main(String[] args) throws Exception{
ClassLoader classLoader = TestClassLoader.class.getClassLoader();
//动态加载一个类
Class rClass = classLoader.loadClass("com.example.reflection.Product" );
Method[] methods = rClass.getMethods();
for (Method method : methods) {
System.out.println("类方法 = " + method.getName());
}
//自定义加载器可以实现ClassLoader类
//在里面读取文件绝对路径或从字节数据内获取类文件信息
//再反映实例化即可
}
}