JAVA class classes and reflection summary __java

Source: Internet
Author: User
Tags reflection

The Java reflection mechanism is in the running state, for any class, all the properties and methods of the class can be known, and any one of its methods and properties can be invoked for any object; This dynamically acquired information, and the function of the method that dynamically invokes the object, is called the reflection mechanism of the Java language.

1. Three ways to get objects of class classes

Get Class object: Public final class<?> getclass (), all generics in reflection are defined as. , the return value is object. obtained by the GetClass () method of the object class

<span style= "color: #000000;" >class person{} public
 class testdemo{public
	 static void Main (string[] args) throws exception{
		per = new person ();
		Class<?> cls = Per.getclass ();
		System.out.println (Cls.getname ());
	}
</span>

Use Class. class to obtain

<span style= "FONT-SIZE:12PX;" > class person{} public
 class testdemo{public
	 static void Main (string[] args) throws exception{
		class& lt;? > CLS = person.class;
		System.out.println (Cls.getname ());
	}
</span>

A static method that is defined internally using class classes

Gets the class class object: public static class<?>forname (String className) throws ClassNotFoundException

Class person{} public
 class testdemo{public
	 static void Main (string[] args) throws exception{
	;? > CLS = class.forname ("person");//Get Class object
		System.out.println (Cls.getname ());
	}

2. Instantiating objects by reflection

Instantiating an object by reflection: Public T newinstance () throws Instantiationexception,illegalaccessexception

Class person{public
	 String toString () {return
		 ' person Class Instance. '
	 }
 }
 public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
	cls = Class.forn Ame ("person");/Get class object
		obj = Cls.newinstance ();  Instantiate the object, and use the keyword new person as per
		= (person) obj;//Downward transition
		System.out.println (per);
	}
 


Example: Factory mode

<span style= "FONT-SIZE:12PX;" >interface fruit{public
	void Eat ();
}
Class Apple implements fruit{public
	void Eat () {
		System.out.println ("Eat an apple.") ");
	}
}
Class factory{public
	static Fruit getinstance (String className) {
		if ("Apple". Equals (ClassName)) {
			Return to New Apple ();
		}
		return null;
	}
}
public class Factorydemo {public
	static void Main (string[] args) {
		Fruit f = factory.getinstance ("Apple"); 
  f.eat ();
	}
</span>


One of the biggest problems in this factory design pattern is: If the subclass of the interface now increases, then the factory class definitely needs to be modified, which is the biggest problem it faces, and the key cause of this biggest problem is new, so if you don't use the keyword new now, it becomes a reflection mechanism.

Interface fruit{public
	void Eat ();
}
Class Apple implements fruit{public
	void Eat () {
		System.out.println ("Eat an apple.") ");
	}
}
Class Orange implements fruit{public
	void Eat () {
		System.out.println ("Eat oranges.") ");
	}
}
Class factory{public
	static Fruit getinstance (String className) {
		Fruit f = null;
		try {
			f = (Fruit) class.forname (className). newinstance (),
		catch (Exception e) {
			e.printstacktrace (); c19/>} return 
		F;
	}
}
public class Factorydemo {public
	static void Main (string[] args) {
		Fruit f = factory.getinstance ("Orange"); 
  f.eat ();
	}

3. Calling the constructor method

Number

Method name return value type description

1

GetConstructors ()

Constructor array

Gets the constructor method that all permissions are public

2

GetConstructor (Class<?>...parametertypes)

Constructor objects

Gets the specified construction method with the permission public

3

Getdeclaredconstructors ()

Constructor array

Get all construction methods, return in declared order

4

Getdeclaredconstructor (Class<?>...parametertypes)

Constructor objects

Gets the specified construction method

<span style= "FONT-SIZE:12PX;" >import Java.lang.reflect.Constructor;
 Class person{Public Person
	 () {} Public person (
	 string name) {} Public person
	 (string name, int age) {}
 }< C5/>public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
		cls = class.fo Rname ("person");//Get Class object
		constructor<?> cons []  = Cls.getconstructors ();  Get all constructs for
		(int x = 0; x < cons.length x + +) {
			System.out.println (cons[x]);
		}
	}
 } </span>


Example: Invoking a structured method with parameters

Import Java.lang.reflect.Constructor;
 Class person{
	 private String name;
	 private int age;
	 Public person (String name, int age) {
		 this.name = name;
		 This.age = age;
	 }
	 Public String toString () {return
		 ' person [name= ' +name+ ', age= ' +age+ '] ';
	 }
 public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
	cls = Class.forn Ame ("person");//Get Class object
		//Get the constructor method of the specified parameter type
	constructor<?> cons = Cls.getconstructor (String.class, Int.class);
		Object obj = cons.newinstance ("John", 20);//pass parameter
		System.out.println (obj) to the constructor;
	 }
 

4. Call the Normal method

Number

Method name return value type description

1

GetMethods ()

Method array

To obtain a method that all permissions are public

2

GetMethod (String name,class<?>...parametertypes)

Method Object

Gets the specified method for the permission public

3

Getdeclaredmethods ()

Method array

Get all methods, return in declared order

4

Getdeclaredmethod (String name,class<?>...parametertypes)

Method Object

Get the specified method

Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Method;
 Class person{
	private String name;
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
 }
 public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
	cls = Class.forn Ame ("person");/Get Class object Method
		met [] = Cls.getmethods ();
		for (int x = 0; x < met.length x + +) {
			System.out.println (met[x]);
		}
	 }
 }


One of the biggest features of the method class object is the ability to invoke the methods in the class using reflection. Call Method:

The public object invoke (object Obj,object...args) throws Illegalaccessexception,illegalargumentexception, Inyocationtargetexception

Import Java.lang.reflect.Method;
 Class person{
	private String name;
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
 }
 public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
	cls = Class.forn Ame ("person");/Get class object
		obj = Cls.newinstance ();
		String attribute = "name"; To invoke the property in the class method
Setmet = Cls.getmethod ("Set" +initcap (attribute), string.class);
		SetName () method
		Getmet = Cls.getmethod (' Get ' +initcap (attribute));
		GetName ()
		setmet.invoke (obj, "John");//equivalent to: Person object. SetName ("John");
		System.out.println (Getmet.invoke (obj));
           Equivalent to: Person object. GetName ()
	 } public
	 static string Initcap (String str) {return
	 str.substring (0,1). toUpperCase (). Concat (str.substring (1));
	 }
 }

5. Call Members

Number

Method name return value type description

1

GetFields ()

Field Array

Get all member variables with public permissions

2

GetField (String name)

Field Object

Gets the specified member variable with the permission public

3

Getdeclaredfields ()

Field Array

Get all member variables, return in declared order

4

Getdeclaredfield (String name)

Field Object

Gets the specified construction method

<span style= "FONT-SIZE:12PX;" >import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
 Class person{
	private String name;
 public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
		cls = Class.fornam E ("person");/Get Class object
		Field field [] = Cls.getdeclaredfields ();
		for (int x = 0; x < Field.length + +) {
			System.out.println (field[x]);
			}
		}
	 } </span>


There are two methods available in the field class: Setting the property contents (similar to: object. Attribute = content):
public void Set (object Obj,object value) throws illegalargumentexcepiton,illegalaccessexception; Get property content (similar to: Object. Properties):
Public Object get (object obj) throws Illegalargumentexception,illegalaccessexception

From the development requirements of the class, it has always been emphasized that the attributes in the class must be encapsulated, so you want to do everything you can to unlock the encapsulation before calling. Release encapsulation: public void Setaccessible (Boolean flag) throws SecurityException;

<span style= "FONT-SIZE:12PX;" >import Java.lang.reflect.Field;
 Class person{
	private String name;
 public class testdemo{public
	 static void Main (string[] args) throws exception{class<?>
	cls = Class.fornam E ("person");//Get class object
		obj = Cls.newinstance ();  Object Instantiation property to allocate space
		Field NameField  = Cls.getdeclaredfield ("name");//Find Name property
		namefield.setaccessible ( true);
		Namefield.set (obj, "John");//person object. Name = "John"
		System.out.println (Namefield.get (obj));
	 }
 </span>

6. Other major descriptive information that can be accessed through reflection

Part

Access method return value type description

Package path

Getpackage ()

Package objects

Get the store path for this class

Class name

GetName ()

String Object

Get the name of the class

Inheriting classes

Getsuperclass ()

Class object

Gets the class that inherits from the class

Implementing interfaces

Getinterfaces ()

Class Array

Get all the interfaces implemented by this class

Inner class

Getclasses ()

Getdeclaredclasses ()

Class Array

Get all internal classes that have permission to public

Get all inner classes

Declaration Class for Inner class

Getdeclaringclass ()

Class object

If the class is an inner class, its member class is returned, or null is returned

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.