Java基础之反射(Reflection)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangshuaionline/article/details/89215727

定义:允许Java在运行期获取指定类中的各种属性的一种机制。(包括接口、变量、方法等信息)

Java反射可获取的属性有:

  1. Class对象
  2. 类名
  3. 构造方法
  4. 包信息
  5. 获取方法、指定方法的参数、返回类型
  6. 变量
  7. 父类
  8. 实现的接口
  9. 修饰符
  10. 泛型

在列举方法之前先具一个包含上面10个属性的例子:

//父类
public class ReflectionFather {
    protected void showFather(){
        System.out.print("父类");
    }
}
//接口(带泛型)
public interface ReflectionInter<T> {
    void show(T t);
}
//实现类(带变量)
public class Reflection extends ReflectionFather implements ReflectionInter<String>{
    public String name = "反射";
    public Reflection(){

    }
    public Reflection(String name){
        this.name = name;
    }
    @Override
    public void show(String s) {
        System.out.print("name是:"+name+"\n"+"泛型是:"+s);
    }
}

  1. 获取Class对象
public class Test {
    public static void main(String[] args) {
        try {
            Class aClass = Class.forName("(路径).Reflection");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
  1. 获取类名
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        System.out.print(aClass.getName());
    }
}

打印结果:

(路径).Reflection
  1. 获取构造方法
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        //返回构造方法列表
        Constructor[] constructors = aClass.getConstructors();
        //获取构造方法
        //Constructor constructor = aClass.getConstructor(new Class[]{String.class});//这个是等价的
        Constructor constructor = constructors[1];
        //获取构造方法参数
        Class[] parameterTypes = constructor.getParameterTypes();
        System.out.print(parameterTypes[0].getName()+"\n");
        //通过构造方法实例化一个类
        try {
            Object obj = constructor.newInstance("新创建");
            Reflection reflection = (Reflection) obj;
            reflection.show("新的");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

打印结果:

java.lang.String
name是:新创建
泛型是:新的
  1. 获取包信息:
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        System.out.print(aClass.getPackage());
    }
}
  1. 获取方法、指定方法的参数、返回类型
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        //获取方法列表
        Method[] methods = aClass.getMethods();
        for(Method method:methods){
//            System.out.print(method.getName()+"\n");
        }
        //通过方法名和返回类型获取method对象
        try {
            Method method = aClass.getMethod("show",new Class[]{String.class});
//            System.out.print(method.getName()+"\n");
            //获取指定方法的参数
            Class[] parameterTypes = method.getParameterTypes();
            //获取指定方法的返回类型
            Class returnType = method.getReturnType();
            //调用方法
            try {
                Object obj = method.invoke(new Reflection(),"不错哦");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

打印结果:

name是:反射
泛型是:不错哦
  1. 获取变量
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        //获取变量
        Field[] fields = aClass.getFields();
        for(Field f:fields){
            System.out.print(f.getName());
        }
    }
}
  1. 获取父类
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        //获取父类
        Class superclass = aClass.getSuperclass();
        System.out.print(superclass.getName());
    }
}
  1. 获取实现的接口:
public class Test {
    public static void main(String[] args) {
        Class aClass = Reflection.class;
        //获取实现的接口
        Class[] interfaces = aClass.getInterfaces();
        for(Class c:interfaces){
            System.out.print(c.getName());
        }
    }
}
  1. 获取修饰符:
public class Test {
    public static void main(String[] args) {
        Class aClass = ReflectionFather.class;
        //获取修饰符
        System.out.print(Modifier.toString(aClass.getModifiers()));
    }
}
  1. 获取泛型:
public class Test {
    List<String> list = new ArrayList<>();

    public static void main(String[] args) {
        Class aClass = Test.class;
        //获取变量
        try {
            Field field = aClass.getDeclaredField("list");
            //获取type
            Type type = field.getGenericType();
            //墙砖成具体的实现类
            ParameterizedTypeImpl parameterizedType = (ParameterizedTypeImpl) type;
            //获取包含泛型的类型
            Type[] genericTypes = parameterizedType.getActualTypeArguments();
            System.out.print(genericTypes[0]);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yangshuaionline/article/details/89215727