Detailed explanation of Java reflection mechanism and application of __ reflection mechanism

Source: Internet
Author: User

1. How to create an instance of class (source of Reflection)

Understand:

Class is an object that corresponds to a run-time class. Equivalent to a Run-time class itself acting as an instance of class

Process:

The source file is compiled (Javac.exe) This step, you need to load the class (through the JVM's class loader)

Recorded in the memory of the cache, each put into the cache of the. class file is a class instance.

Java.lang.Class is the source of reflection.

Next, the classes involved are under the Java.lang.reflect sub package

such as: Field methodconstructor Type Package

Call GetMethods through the class instance to get all the methods, Getcontructors () get all the constructor

How to instantiate the class

1. Call the. Class attribute of the Run-time class such as: Class Clazz1=person.class;;

2. Invoke the object of the class, call its GetClass method such as: Person p=new person (); Classclazz2=p.getclass ();

3. Call class static method forname (String ClassName) This method reports classnotfoundexception such as:; Class clazz3=class.forname ("1.txt");

4. Loader via class: Classloaderloader=this.getclass (). getClassLoader (); Class Clazz4=loader.loadclass ("1.txt");

2. What can be done after the class instance: (See demo)

2.1 You can create an object of the corresponding Run-time class

2.2 You can get the complete class structure of the corresponding Run-time class: Properties, methods, constructors, packages, parent classes, interfaces, generics, annotations, exceptions, inner classes ... Such as:

Method[] M1=clazz,getmethods () gets the corresponding Run-time class (the declared public method), (containing the parent class)

Method[] M2=clazz.getdeclaredmethod () gets all public or private methods (not including parent classes) of the corresponding Run-time class itself (any permissions)

2.3 You can call the struct specified in the Run-time class (a specified property, method, constructor) (see demo)

3. Dynamic Agent--reflection of the application, realize the dynamic of reflection

Package Mynetdemo;

Import Javax.print.attribute.standard.Sides;

public class Animal {
	private String name;
	public int age;
	Static String desc= "I am a little animal";
	Public Animal () {
		super ();
		System.out.println (the initial constructor for the test clazz.instance () call is this. ");
	}
	
	Test how to invoke the private constructor, using reflection
	private Animal (String Name,int age) {
		super ();
		This.name=name;
		this.age=age;
	}
	
	@Override public
	String toString () {return
		"Animal [name=" + name + ", age=" + Age +  "]";
	}

	public static void info () {
		System.out.println ("Animal");
	}
	
	Public String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}

	To test a method that invokes a private method
	private int getage () {return age
		;
	}

	public void Setage (int age) {
		this.age = age;
	}

	public static String GetDesc () {return
		desc;
	}

	public static void Setdesc (String desc) {
		ANIMAL.DESC = desc;
	}

	public void Show (String desc) {
		System.out.println ("I am A," +desc);
	}
	
	


Package Mynetdemo;
Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Field;

Import Java.lang.reflect.Method;

Import Org.junit.Test; public class Testreflection {//calls the specified method @Test public void Test4 () throws Exception {class clazz = Class.forName ("My
		Netdemo.animal ");
		Object obj = clazz.newinstance ();

		Animal a = (Animal) obj;
		Invoke Private Method m1 = Clazz.getdeclaredmethod ("Getage");
		M1.setaccessible (TRUE);
		int age = (int) m1.invoke (a);/The return value of the method is the return value of Getage () System.out.println (age);
		Call public methods m2 = Clazz.getmethod ("show", String.class);
		Object returnval = M2.invoke (A, "kitten");
		System.out.println (returnval); The return value of the//show method, or null if void//Call static method M3=clazz.getdeclaredmethod ("info");
		M3.setaccessible (TRUE);
		M3.invoke (a);
		M3.invoke (Animal.class);
	M3.invoke (NULL);
		//invokes the specified property @Test public void Test3 () throws Exception {Class clazz = Class.forName ("Mynetdemo.animal");
		Object obj = clazz.newinstance (); AnimAl a = (Animal) obj;
		Call Private Property Field F1 = Clazz.getdeclaredfield ("name");
		F1.setaccessible (TRUE);

		F1.set (A, "Jerry");
		Call common Property Field F2 = Clazz.getfield ("Age");
		F2.set (A, 9);
		System.out.println (a);

		To get a property, is to get the property of the object System.out.println (F2.get (a));
		Call static property Field F3 = Clazz.getdeclaredfield ("desc");
		System.out.println (F3.get (Animal.class));
		System.out.println (F3.get (a));

	SYSTEM.OUT.PRINTLN (F3.get (null));

		//Call the specified constructor to call the Run-time object @Test public void Test2 () throws Exception {Class clazz = Animal.class;  Constructor C = Clazz.getdeclaredconstructor (String.class, int.class);//Invoke Private method C.setaccessible (TRUE);//Set access Permissions Animal
		A = (Animal) c.newinstance ("Tom", 10);
	System.out.println (a);
		//Get Run-time objects in a way @Test public void test1 () throws Exception {Class clazz = Class.forName ("Mynetdemo.animal");
		Object obj = Clazz.newinstance ();//Creates a Run-time object, the default invocation is the null parameter constructor Animal a = (Animal) obj;
	System.out.println (a);
 }

}

Related Article

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.