Type information (reflection, RTTI)

Type of information

1.java runtime information about how to identify objects and classes

  • "Traditional" RTTI run-time type identification, we assume that we already know at compile time, all types, open and check the .class file at compile time

  • Reflection, and allows discovery information using classes at runtime, the file is opened and checked at runtime .class

Run-time type information so that you can find and use information on the type of program runs

2.Class objects

Class objects of this particular object class contains information about
each class has a Class object, stored in the .class file of the same name compiled in

noun

Class loader subsystem

Native class loader

All classes are their first time use, dynamically loaded into the JVM, when you create the first program class static member references , they will load the class

The constructor also static methods, new at the time of the creation of a new object class, will be treated as references to static member of the class

java runtime, not all the classes fully loaded, but loaded only when needed

static initialization time class load is carried out

Whenever you want to use at run-time type information, you must first obtain the appropriate Class object reference

How to obtain a reference to the Class object?

  • Class.forName ( "the class name"), do not need to hold objects of that type can be obtained objects

  • T.class, class literals (Note, create a reference to the Class object of this method does not automatically initialize the Class object)

  • Object.getClass (), has the type of object, use the method to obtain direct

  • getSuperclass (), has a Class object, direct access to the base class

The actual work step class

  • Loading, class loader performs
  • Link, the class bytecode verification, the static allocation of storage space domain
  • Initializing, superclass initialization, and performing static initialization static initializer block

Initialization is delayed until the static method (constructor is static) or non-constant static field for the first time cited before execution

import java.util.Random;
/**
 * ClassInitialization
 * @@author thinking in java
 * @@version 1.1
 */
class Initable{
    // 编译器常量
    static final int staticFinal=1;
    // 不是编译器常量
    static final int staticFinal2=ClassInitialization.rand.nextInt(1000);
    static{
        System.out.println("initializing Initable");
    }
}
class Initable2{
    static int staticNonFinal=2;
    static{
        System.out.println("initializing Initable2");
    }
}
class Initable3{
    static int staticNonFinal=3;
    static{
        System.out.println("initializing Initable3");
    }
}
public class ClassInitialization{

    public static Random rand=new Random(47);

    public static void main(String[] args) throws Exception{
        //  使用.class获得类的引用不会引发初始化
        Class initable=Initable.class;
        System.out.println("after creating initable ref");
        //  static final 编译器常量,可以不对类进行初始化就可进行读取
        System.out.println(Initable.staticFinal);
        // 触发类的初始化
        System.out.println(Initable.staticFinal2);
        // static 或 final 在读取前必须进行链接(分配存储空间)和初始化(初始化存储空间)
        System.out.println(Initable2.staticNonFinal);
        // Class.forName() 立即进行初始化
        Class initable3=Class.forName("Initable3");
        System.out.println("after creating initable3 ref");
        System.out.println(Initable3.staticNonFinal);

    }
}
/*output:
after creating initable ref
1
initializing Initable
258
initializing Initable2
2
initializing Initable3
after creating initable3 ref
3
*///:~

instanceof

It returns a Boolean value that tells us that the object is not an instance of a particular type of

There is also a method Class

public boolean isInstance(Object obj);

reflection

RTTI restrictions would like to know the exact type of an object, there is a limit, this type must be known at compile time

Obtaining a reference space, not in the program, Class.forName ( "com.mysql.cj.DriverManger");
or obtained from the network, the bytes of a disk class representatives

Class and class libraries java.lang.reflect full support of the entire reflection concept

  • Filed, using get, set to modify the relevant fields Field
  • Method, invoke () method call to achieve
  • Constructor, construction of new objects

Reflection is used to support other properties will be used to create dynamic code (serialization, javaBean)

Creating instances reflection

// Class的newInstance()
Class<?> c=String.class;
Object str=c.newInstance();

// Class的Constructor对象,可以指定构造器来实现
Class<?> c=String.class;
Constructor constructor=c.getConstructor(String.class);
Object obj=constructor.newInstance("456");

Obtaining configuration information
getConstructor method to obtain an instance of class Class Constructor class
and newInstance Constructor class has a method to create an object instance

// 类的所有公有构造器
public Constructor[] getConstructors()

// 类的所有构造器
public Constructor[] getDeclareConstructors()

Acquisition method
to obtain a Class object methods collection

// 返回类的公有方法,包含继承的公有方法数组
public Method[] getMethods() throws SecurityException

// 返回类的所有方法,不包括由超类继承的方法
public Method[] getDeclareMethods() throws SecurityException

// 返回一个特定的方法

public Method getMethod(String name,Class<?>...parameterTypes);

Obtaining field information

// 返回一个字段域,记录了类和超类的公有域
public Filed[] getFields()

// 记录类的全部域,以声明的成员变量,不能得到父类的成员变量
public Field[] getDeclareFields()

Call the method

// 函数原型
public Object invoke(Object obj,Object ...args)
              throws IllegalAccessException, IllegalArgumentException,InvocationTargetException


// 一个测试用例
public class test1 {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> klass = methodClass.class;
        //创建methodClass的实例
        Object obj = klass.newInstance();
        //获取methodClass类的add方法
        Method method = klass.getMethod("add",int.class,int.class);
        //调用method对应的方法 => add(1,4)
        Object result = method.invoke(obj,1,4);
        System.out.println(result);
    }
}
class methodClass {
    public final int fuck = 3;
    public int add(int a,int b) {
        return a+b;
    }
    public int sub(int a,int b) {
        return a+b;
    }
}

Reflection of the advantages and disadvantages

If you do not have a reflection function is completed, do not use reflection

advantage:

  • Scalability, fully qualified name may be used to create instances of objects may be expanded, using a custom class from the outside

  • Class Browser and visual development tools, idea, escipse display prompts class, is reflected applications

  • Debug and test tools,

Disadvantages:

  • Performance overhead, a dynamic type resolution, the JVM can not optimize the code, a low reflection efficiency

  • Security restrictions, you must run in an environment free of security restrictions

  • Internal exposure, the abstract reflection code undermine

reference:

Depth analysis of Java reflection (1) - Basic (sczyh30)
Thinking in the Java
Java core technology (Volume -)
Technical Interview essential -CyC2018

Guess you like

Origin www.cnblogs.com/GeekDanny/p/11829475.html