java interview - reflection

1. What is a reflection? What are the advantages and disadvantages?

  Reflection is dynamically loaded objects, and objects to analyze. In the operating state, for any class, they are made known to all properties and methods of this class. For any object, you can call any of its methods. This dynamic access to information and dynamic invocation object methods feature called java reflection mechanism.
  Advantages: reflective objects can dynamically create and compile, to maximize the flexibility of java.
  Disadvantages: impact on performance. Is basically a reflection explanation operation, JVM tell us what to do and meet our needs, such operations are always slower than direct execution of java code.

2, How to use reflection?

  a: Create an object by a fully qualified class name

Class<?> clz = Class.forname("全限类名");

Class<?> clz = A.class;

Class<?> clz = b.getClass();

  b: obtaining constructor object, the new object constructor

Constructor<?> cons = clz.getConstructor([参数类型class]);
cons.newInstance([参数]);

  c: create an instance of an object class by (equivalent new class name () constructor with no arguments)

clz.newInstance();

  d: a property of the object obtained by the object class

Field[] fields = clz .getFields();//获得某个类的所有的公共(public)的字段,包括父类中的字段。

Field[] fields = clz .getDeclaredFields();//获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段

  e: is obtained by a method of an object class object

Method m = clz.getMethod("方法名",参数class);//只能获取公共的

Method M = clz.getDeclaredMethod("方法名",参数class)//获取任意修饰的方法,不能执行私有

m.setAccessible(true);//让私有的方法可以执行

  f: Let execution method

m.invoke(obj实例对象,obj可变参数)

Guess you like

Origin www.cnblogs.com/ssl-bl/p/11032748.html