Reflection, java reflection

Source: Internet
Author: User

Reflection, java reflection

1. Why use reflection?

Classes that are completely unknown during compilation need to be known and used during runtime, so as to create their objects, change their attributes, and call their methods.

2. What is reflection?

During running, the program can use the Reflection API to obtain internal information of any class and directly manipulate its attributes and methods.

3. How does one load classes?

When a Program actively uses a class, the class has not been loaded into the memory, and the system will load the class through the following three steps.

① Class loading: Read the. Class file into the memory and create a class object for it. Completed by the class loader.

② Class connection: Merge binary files of the class into JRE.

③ Class initialization: The JVM initializes the class.

4. Category of the Class Loader

System Class Loader

ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

② Extended Class Loader

ClassLoader parent = ClassLoader.getSystemClassLoader().getParent();

③ Boot Class Loader: responsible for loading core class libraries and cannot be directly obtained

ClassLoader parent = ClassLoader.getSystemClassLoader().getParent().getParent();

5. class loading time

① The source file program is loaded only when the program code is required.

② Class code is loaded only when used for the first time.

<1> usually occurs when the first object is created.

<2> access to static domains and static objects is also loaded.

<3> creating object references does not load classes.

<4> the class is initialized when a static member is accessed, because the constructor is also an implicit static method. Therefore, more accurately, classes are loaded when any static member accesses them.

6. Four Methods for getting Class objects

Class clazz = Person.class;

Person person = new Person();Class<? extends Person> clazz = person.getClass();

Class<?> clazz = Class.forName("com.nucsoft.refletciton.Person");

String className = "com.nucsoft.jdbc.Person";ClassLoader classLoader = Person.class.getClassLoader();Class<?> clazz = classLoader.loadClass(className);

7. Create an instance through reflection

① It is created by the no-argument constructor by default.

String className = "com.nucsoft.jdbc.Person";Class<?> clazz = Class.forName(className);Object newInstance = clazz.newInstance();

② You can also create an object by using a parameter constructor.

Class<?> personClass = Class.forName("com.nucsoft.refletciton.Person");Constructor<?> constructor = personClass.getConstructor(int.class, String.class);Object obj = constructor.newInstance(2, "wangwu");

8. Get attributes through reflection and change attributes

① The getField () method can only obtain attributes modified by public.

② The getDeclaredField () method can obtain attribute objects (Field objects) modified by any modifier ). However, when modifying a private attribute, you must change the access permission.

Class<?> personClass = Class.forName("com.nucsoft.refletciton.Person");Field personName = personClass.getDeclaredField("personName");personName.setAccessible(true);personName.set(person, "zhangsan");

9. Obtain the method through reflection and call the Method

The getMethod () method can only obtain the public modifier.

② The getDeclaredMethod () Method can modifier any Method object ). However, when calling a non-public method, you must set the access permission. It is called by method. invoke (obj, args,

Method sayMethod = personClass.getDeclaredMethod("say");sayMethod.setAccessible(true);sayMethod.invoke(person);

10. Obtain the parent class generic

 Class clazz = Person.class; Type type = clazz.getGenericSuperClass(); ParameterizedType types = (ParameterizedType)type; for(Type t : types) { System.out.println(t); }

11. Static proxy

Public interface Factory {void produce ();} public class NikeFactory implements Factory {@ Override public void produce () {System. out. println ("produce Nike clothes ..... ") ;}} public class NikeProxy implements Factory {private NikeFactory nikeFactroy = null; public NikeProxy (NikeFactory nikeFactory) {this. nikeFactroy = nikeFactory;} @ Override public void produce () {nikeFactroy. produce () ;}} public static void main (String [] args) {NikeFactory nikeFactory = new NikeFactory (); NikeProxy nikeProxy = new NikeProxy (nikeFactory); nikeProxy. produce ();}Static proxy

12. Dynamic proxy

Public interface Factory {void produce ();} public class NikeFactory implements Factory {@ Override public void produce () {System. out. println ("produce Nike clothes ..... ") ;}} public class MyInvocationHandler implements InvocationHandler {Object obj = null; public Object getProxy (Object obj) {this. obj = obj; return Proxy. newProxyInstance (obj. getClass (). getClassLoader (), obj. getClass (). getInterfaces (), this) ;}@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {return method. invoke (obj, args) ;}} public class DynamicProxy {public static void main (String [] args) {NikeFactory nikeFactory = new NikeFactory (); MyInvocationHandler myInvocationHandler = new MyInvocationHandler (); object obj = myInvocationHandler. getProxy (nikeFactory); Factory factory = (Factory) obj; factory. produce ();}}Dynamic proxy

13. AOP

Public interface Human {void walk (); void fly ();} public class SuperMan implements Human {@ Override public void walk () {System. out. println ("walking and walking! ") ;}@ Override public void fly () {System. out. println ("I belive I can fly... ") ;}} public class MyInvocationHandler implements InvocationHandler {Object obj = null; public Object getProxy (Object obj) {this. obj = obj; return Proxy. newProxyInstance (obj. getClass (). getClassLoader (), obj. getClass (). getInterfaces (), this) ;}@ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {HumanUtil. before (); Object returnValue = method. invoke (obj, args); HumanUtil. after (); return returnValue;} public class HumanUtil {public static void before () {System. out. println ("HumanUtil's before... ");} public static void after () {System. out. println ("HumanUtil's after... ") ;}} public class AopTest {public static void main (String [] args) {SuperMan superMan = new SuperMan (); MyInvocationHandler myInvocationHandler = new MyInvocationHandler (); object proxy = myInvocationHandler. getProxy (superMan); Human human = (Human) proxy; human. walk (); System. out. println ("--------------------"); human. fly ();}}AOP

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.