java 反射学习

1.Class.forName();
2.newInstance //用这个方法必须保证类中有无参构造器
3.getClassLoader
4.Method[] methods=clazz.getMethods();//通过反射得到反射类中的方法都有哪些,但值得注意的是不能获取私有方法
即以private修饰的方法
5.clazz.getDeclaredMethods()方法能够获取所有的反射方法,包括私有方法!,并且只获取当前类中的方法
6.通过反射获取方法的目的是执行该方法,那么如何执行呢??
method.invoke(Object obj,parmaters);方法
7.获取父类的方法:clazz.getsuperClass()
8.一般情况下通过反射能够获得反射对象的私有方法,但是用method.invoke()方法不能够执行,需要特殊的处理
需要用到 method.setAccessible(true)这个方法(这个写到method.inoke()方法的前面)

9.获取父类中的方法(私有或非私有)
使用了一个for循环:
for(;clazz!=Object;clazz=clazz.getSuperClass)

10.上面主要是通过反射找到method,下面是找到字段Field
与反射获取method一样的方法,有getField,getDeclaredField等等

11.
Field: 封装了字段的信息.
* 1. 获取字段:
* 1.1 Field [] fields = clazz.getDeclaredFields();
* 1.2 Field field2 = clazz.getDeclaredField("age");
*
* 2. 获取指定对象的指定字段的值.
* public Object get(Object obj)
* obj 为字段所在的对象.
*
* Object val = field.get(person);
*
* 注意: 若该字段是私有的, 需先调用 setAccessible(true) 方法
*
* 3. 设置指定对象的指定字段的值
* public void set(Object obj, Object value)
* obj: 字段所在的对象
* value: 要设置的值.
*
* field.set(person, "atguigu");

//1. 获取字段
//1.1 获取 Field 的数组
Field [] fields = clazz.getDeclaredFields();
for(Field field: fields){
System.out.println(field.getName());
}

//1.2 获取指定名字的 Field
Field field = clazz.getDeclaredField("name");
System.out.println(field.getName());

Person person = new Person("ABC", 12);
//2. 获取指定对象的 Field 的值
Object val = field.get(person);
System.out.println(val);

//3. 设置指定对象的 Field 的值
field.set(person, "atguigu");
System.out.println(person.getName());

//4. 若该字段是私有的, 需要调用 setAccessible(true) 方法
Field field2 = clazz.getDeclaredField("age");
field2.setAccessible(true);
System.out.println(field2.get(person));

12.如何利用反射调用有参数的构造器呢?
利用反射先得到构造器:Constructor<> constructor=clazz.getConstructor;
constructor.newInstance(参数列表)

13.利用反射获取注释Annotation:
这个和获取Field和Method不太一样,因为它不是通过clazz获取的,
它是通过Method.getAnnotation获取的

14.反射与泛型:其实实质上还是为了获取子类的带泛型的父类的泛型类型,另外还有一个知识点:记住一点:在构造子类时,一定会调用到父类的构造方法。
用到的方法:
Type接口(普通的和带参数的Type( ParameterizedType))
使用clazz.getGenericSuperclass() 获得Type接口。此时返回的不仅仅是父类的class,更重要的是返回的是
带泛型的父类Class,并且把这个返回值传给Type接口,但是这个普通的Type接口不能返回参数(父类class中的泛型)
所以需要对这个Type接口进行强转,转成ParameterizedType接口,然后在通过ParameterizedType的getActualTypeArguments()
方法,返回一个Type[] 数组,(因为父类可能会带多个泛型参数),这个数组的索引是从0开始的,也就是Type[0]
就是父类中的第一个泛型类型。

完整的实例如下:
//获取 Dao 子类的父类
// Class clazz2 = this.getClass().getSuperclass();
// System.out.println(clazz2); //Dao

//获取 Dao 子类的带泛型参数的父类: Dao<Person>
Type type = this.getClass().getGenericSuperclass();

//获取具体的泛型参数
if(type instanceof ParameterizedType){
ParameterizedType parameterizedType =
(ParameterizedType) type;

Type [] args = parameterizedType.getActualTypeArguments();
// System.out.println(Arrays.asList(args));

if(args != null && args.length > 0){
Type arg = args[0];

if(arg instanceof Class){
clazz = (Class<T>) arg;
}
}
}
}
15.动态代理:
实例:
final ArithmeticCalculator arithmeticCalculator =
new ArithmeticCalculatorImpl2();

ArithmeticCalculator proxy =
/**
* ClassLoader: 由动态代理产生的对象由哪个类加载器来加载.
* 通常情况下和被代理对象使用一样的类加载器
* Class<?>[]: 由动态代理产生的对象必须需要实现的接口的 Class 数组
* InvocationHandler: 当具体调用代理对象的方法时, 将产生什么行为.
*/
(ArithmeticCalculator) Proxy.newProxyInstance(
arithmeticCalculator.getClass().getClassLoader(),
new Class[]{ArithmeticCalculator.class},
new InvocationHandler() {
/**
* proxy:
* method: 正在被调用的方法
* args: 调用方法时传入的参数.
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// System.out.println("method: " + method);
// System.out.println(Arrays.asList(args));

System.out.println("^_^ The method "
+ method.getName() + " begins with "
+ Arrays.asList(args));

//调用被代理类的目标方法
Object result = method.invoke(arithmeticCalculator, args);

System.out.println("^_^ The method "
+ method.getName()
+ " ends with " + result);

return result;
}
});

proxy.mul(1, 2);

int result = proxy.add(2, 5);
System.out.println(result);
注意事项:
* 关于动态代理的细节
* 1. 需要一个被代理的对象.
* 2. 类加载器通常是和被代理对象使用相同的类加载器
*
* 3. 一般地, Proxy.newInstance() 的返回值是一个被代理对象实现的接口的类型.
* 当然也可以是其他的接口的类型.
* 注意: 第二个参数, 必须是一个接口类型的数组.
* 提示: 若代理对象不需要额外实现被代理对象实现的接口以外的接口,
* 可以使用 target.getClass().getInterfaces()
*
* 4. InvocationHandler 通常使用匿名内部类的方式: 被代理对象需要是 final 类型的.
* 5. InvocationHandler 的 invoke() 方法中的第一个参数 Object 类型的 proxy
* 指的是正在被返回的那个代理对象, 一般情况下使用.

ReflectionUtils:代码:

package com.atguigu.javase.lesson12;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 反射的 Utils 函数集合
 * 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
 * @author Administrator
 *
 */
public class ReflectionUtils {

    
    /**
     * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     * @param clazz
     * @param index
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Class getSuperClassGenricType(Class clazz, int index){
        Type genType = clazz.getGenericSuperclass();
        
        if(!(genType instanceof ParameterizedType)){
            return Object.class;
        }
        
        Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
        
        if(index >= params.length || index < 0){
            return Object.class;
        }
        
        if(!(params[index] instanceof Class)){
            return Object.class;
        }
        
        return (Class) params[index];
    }
    
    /**
     * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     * @param <T>
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static<T> Class<T> getSuperGenericType(Class clazz){
        return getSuperClassGenricType(clazz, 0);
    }
    
    /**
     * 循环向上转型, 获取对象的 DeclaredMethod
     * @param object
     * @param methodName
     * @param parameterTypes
     * @return
     */
    public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){
        
        for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
            try {
                //superClass.getMethod(methodName, parameterTypes);
                return superClass.getDeclaredMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                //Method 不在当前类定义, 继续向上转型
            }
            //..
        }
        
        return null;
    }
    
    /**
     * 使 filed 变为可访问
     * @param field
     */
    public static void makeAccessible(Field field){
        if(!Modifier.isPublic(field.getModifiers())){
            field.setAccessible(true);
        }
    }
    
    /**
     * 循环向上转型, 获取对象的 DeclaredField
     * @param object
     * @param filedName
     * @return
     */
    public static Field getDeclaredField(Object object, String filedName){
        
        for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
            try {
                return superClass.getDeclaredField(filedName);
            } catch (NoSuchFieldException e) {
                //Field 不在当前类定义, 继续向上转型
            }
        }
        return null;
    }
    
    /**
     * 直接调用对象方法, 而忽略修饰符(private, protected)
     * @param object
     * @param methodName
     * @param parameterTypes
     * @param parameters
     * @return
     * @throws InvocationTargetException 
     * @throws IllegalArgumentException 
     */
    public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
            Object [] parameters) throws InvocationTargetException{
        
        Method method = getDeclaredMethod(object, methodName, parameterTypes);
        
        if(method == null){
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
        }
        
        method.setAccessible(true);
        
        try {
            return method.invoke(object, parameters);
        } catch(IllegalAccessException e) {
            System.out.println("不可能抛出的异常");
        } 
        
        return null;
    }
    
    /**
     * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
     * @param object
     * @param fieldName
     * @param value
     */
    public static void setFieldValue(Object object, String fieldName, Object value){
        Field field = getDeclaredField(object, fieldName);
        
        if (field == null)
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        
        makeAccessible(field);
        
        try {
            field.set(object, value);
        } catch (IllegalAccessException e) {
            System.out.println("不可能抛出的异常");
        }
    }
    
    /**
     * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
     * @param object
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object object, String fieldName){
        Field field = getDeclaredField(object, fieldName);
        
        if (field == null)
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        
        makeAccessible(field);
        
        Object result = null;
        
        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            System.out.println("不可能抛出的异常");
        }
        
        return result;
    }
}
原文地址:https://www.cnblogs.com/zhangshitong/p/4946241.html