Home  >  Article  >  Java  >  08.Java Basics - Reflection

08.Java Basics - Reflection

黄舟
黄舟Original
2017-02-27 10:35:231098browse


Basic concepts


##Java reflection mechanism allows us to )

Outside of the runtime (Runtime) Check the information of classes, interfaces, variables and methods. The functions of reflection are as follows:

For any class, you can know all the properties and methods of this class;
  • For any object, you can call any of its methods and properties.
Class

#To obtain information about a class, you first need to obtain the Class object of the class.

All types in Java include basic types (int, long, float, etc.), even arrays have Class objects associated with them.

    Get the object of the class
  • //1.在编译期获取类对象Class cls = Demo.class 
    
    //2.在运行期获取类对象(注意:需要包括完整的包名) Cllss clas = Class.forName("com.test.Demo")

    Get the name of the class
  • Class cls = ...// 1.获取完整类型(包括包名)String className = cls.getName();
    // 2.获取简单类名 String simpleClassName =cls.getSimpleName();

    Get the class modifier
  • Class cls = ...// 修饰符都被包装成一个 int 类型的数字,这样每个修饰符都是一个位标识(flag bit)    
    int modifiers  = cls.getModifiers();// 判断修饰符类型Modifier.isPublic( modifiers);
    Modifier.isProtected( modifiers);
    Modifier.isPrivate( modifiers);
    Modifier.isAbstract( modifiers);
    Modifier.isInterface( modifiers);
    Modifier.isFinal( modifiers);
    Modifier.isStatic( modifiers);
    Modifier.isNative( modifiers);
    Modifier.isStrict( modifiers);
    Modifier.isSynchronized( modifiers);
    Modifier.isTransient( modifiers);
    Modifier.isVolatile( modifiers);

    Get the package information where the class is located
  • Class cls =...
    Package p = cls.getPackage();

    Get the parent class that the class inherits
  • Class cls = ...
    Class superClass  = cls.getSuperclass();

    Get the interface type implemented by the class
  • Class cls = ...// 类可以实现多个接口,因此返回的是接口数组Class [ ] interfaces = cls.getInterfaces();

Constructor

In Java, the Constructor class represents a constructor object.

Get
    Public
  • Constructor method

    Class cls = ...// 1.获取所有构造函数Constructor[] constructors = cls.getConstructors(); 
    
    // 2.获取指定构造函数,不存在匹配则抛出异常。
    // 对应的构造函数入参类为 Person(String str, int i)Constructor constructor = 
        cls.getConstructor(new Class[]{String.class,int.class});

    Get the input parameters of the constructor Type
  • Constructor constructor = ...
    // 因为构造函数的入参有多个,因此返回的数组Class [] paramterTypes = constructor.getParameterTypes();
    for(Class paramterType: paramterTypes ){    
    // do something...}

    Constructor Instantiation Class
  • Class cls = ...
    Constructor constructor = cls.getConstructor(new Class[]{String.class});
    // Object[] 数组表示入参的具体值,需要与 Class[] 的入参类型完全匹配Demo demo = (Demo) constructor.newInstance(new Object[]{"hello"});

Field

In Java, the Field class represents a variable object.

    Get all variables (public, non-public)
  • Class cls = ...// 1.获取所有公共变量Field[] fields = cls.getFields();
    // 2.获取所有非公共变量Field [] privateFields =cls.getDeclaredFields();

    Get Specify variables (public, non-public)
  • Class cls = ...//入参为变量名称,名称不匹配则抛出异常// 获取指定公共变量Field field = cls.getField("num");
    // 获取指定非公共变量Field privateField = cls.getDeclaredField("str");

    Manipulate variables
  • Class<?> cls = Demo.class;
    Demo demo = (Demo) cls.newInstance();// 1.1.公共方法的 setter、getterField field = cls.getField("num");
    field.set(demo, 1000);int filedValue  = (Integer) field.get(demo);// 2.1 非公共方法的 setter、getterField privateField = cls.getDeclaredField("str");
    privateField.setAccessible(true); // 关键 -> 操作之前,需要设置访问权限privateField.set(demo, "hello");
    String privateFieldValue = (String) privateField.get(demo);

Method

1. Get the method object

    Get all methods
  • Class cls = ...// 1.获取所有公共方法(包括从父类继承而来的)Method[] methods = cls.getMethods();
    // 2.获取所有非公共方法(包括从父类继承而来的)Method [] privateMethods = cls.getDeclaredMethods();

    Get the specified method
  • Class cls = ...// 1.获取指定公共方法,入参为:方法名、方法入参Method method = cls.getMethod("print", new Class[]{String.class});
    // 2.获取指定非公共方法,入参为:方法名、方法入参Method privateMethod = cls.getDeclaredMethod("say", new Class[]{int.class});

    Get Parameter type of method
  • Method method = ...// 1.获取方法的所有入参类型Class [] paramterTypes = method.getParameterTypes();
    // 2.获取方法的返回值类型Class reeturnType = method.getReturnType();

    Execution method
  • Class cls = Demo.class;
    Demo demo = (Demo) cls.newInstance();
    Method method = cls.getMethod("print", new Class[]{String.class});//1.执行公用方法,入参为:类实例,方法入参的具体值method.invoke(demo, "hello");
    //2.执行非公共方法Method privateMethod = 
        cls.getDeclaredMethod("print", new Class[]{String.class});
    privateMethod.setAccessible(true); // 关键 -> 操作之前,需要获得访问权限privateMethod.invoke(demo, "hello");

    Judge getter/setter methods
  • public static boolean isGetter(Method method){    
    if(!method.getName().startsWith("get")){        
    return false;
        }    
        if(method.getParameterTypes().length !=0){        
        return false;
        }    
        if(void.class.equals(method.getReturnType())){        
        return false;
        }    
        return true;
    }
    public static boolean isSetter(Method method){    
    if(!method.getName().startsWith("set")){        
    return false;
        }    
        if(method.getParameterTypes().length !=1){        
        return false;
        }    
        return true;
    }

Array

In Java, use the Array class Represents an array object.

    Get the array object
  • int [ ] intArray = ... 
    Class arrayCls = intArray.class;

    Get the array member type
  • Class arrayCls = ...
    Class arrayComponentType =arrayCls .getComponentType();

    Create array
  • // 创建一个数组,类型为 int ,容量为 3int [ ] intArray = (int[]) Array.newInstance(int.class, 3);
    //在 JVM 中字母I代表int类型,左边的‘[’代表我想要的是一个int类型的数组Class intArrayClass = Class.forName("[I");  
    
    //注意‘[L’的右边是类名,类名的右边是一个‘;’符号。这个的含义是一个指定类型的数组。
     stringArrayClass = Class.forName("[Ljava.lang.String;");

    Add Array elements
  • int [ ] intArray = ...// 添加元素,数组为 intArray,位置为 0 ,值为 100Array.set(intArray, 0, 100);
    Array.set(intArray, 1, 200);
    System.out.println("intArray[0] = " + Array.get(intArray, 0));
    System.out.println("intArray[1] = " + Array.get(intArray, 1));

    The above is the content of 08.Java Basics - Reflection. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn