Java reflection Technical Overview

1. What is Java reflection?

  Is running, dynamic access to all the information the class

2. The role of reflection

  . A decompiler: .class -> java.

  b. Thoroughly reflection mechanism, access to the Java object properties, methods, and other construction methods

3. The application scenario of reflection

  Jdbc load the driver

  SpringIOC achieve

  Java framework

4. Create an object in two ways

  a. Direct new Object

  b. Using reflective

    Create an object using reflection of two ways:

      The first, using the test class without constructor parameter

        1.Class<?> forName = Class.forName("com.nvdi.iloveyou.TestBean");

        2.Object newInstance = forName.newInstance();  

        3.TestBean testBean = (TestBean) newInstance;

        Note: TestBean as a test class, com.nvdi.iloveyou.TestBean for the full path of the test class

          NewInstance principle of creating an object is created using non-parametric test constructor of the class

      Second, using the test class with a constructor parameter

        1.Class<?> forName = Class.forName("com.nvdiiloveyou.TestBean");

        2.Constructor<?> constructor = forName.getConstructor(String.class);

        3.Object newInstance = constructor.newInstance("11");

        4.TestBean testBean = (TestBean) newInstance;

        NOTE: String.class test class has constructor parameter of the parameter type

          "11" as a test class constructor parameter has the value of the parameter

    Get all the methods use reflection test class

        1.Class<?> forName = Class.forName("com.nvdiiloveyou.TestBean");

        2.Method [] = methods forName.getDeclareMethods ();

    Get all the properties of a reflective test class

        1.Class<?> forName = Class.forName("com.nvdiiloveyou.TestBean");

        2.Field [] = declaredFields forName.getDeclaredFields ();

        NOTE: getDeclareMethods (), getDeclaredFields () to get the current class are all methods and properties, and can not

          Get parent class attributes and methods, the parent class wants to get all of the methods can be used getMethod ()

       Reflective properties of all test access class, including the private property

        1.Class<?> forName = Class.forName("com.nvdiiloveyou.TestBean");

        2.Field declaredField = forName.getDeclaredField("userId");

        3.Object forName.newInstance obj = ();

        4.declaredField.setAccessible(true);

        4.declaredField.set(obj, "123");

        5.TestBean testBean = (TestBean) obj;

        Note: userId test class private property

          Step 4 setAccessible set to true, indicates to allow access to a private property test class

5. Create an object using reflection and new, which high efficiency?

  new high efficiency to create objects

Guess you like

Origin www.cnblogs.com/zyybb/p/11080019.html
Recommended