Java reflection Class -- class, java reflection -- Class

Source: Internet
Author: User

Java reflection Class -- class, java reflection -- Class

Let's first look at the functions provided by reflection:

The reflection mechanism provides the function to determine the data type, parse the class structure, and obtain internal information when loading the runtime.

Operate on this type or instance, access attributes, call methods, and create new objects


WHO provides java reflection?

The Class object is provided, but you must first obtain the object through JVM and create a Class object.


There are three methods to create a Class object:

Use the forName () Static Method of the Class, for example, Class. forName (java. lang. reflect. Field)

Call the class attribute of the Class to obtain the corresponding class object,

Call the getClass () method of an object

Obtain the real information of the Class Object.

For example, object constructors, attributes, methods, annotations, interfaces, parent classes, annotations (must have source code; otherwise, annotations cannot be found), etc.

For example:

Constructor <?> Getconstructors () returns all public constructors identified by the class Object Method [] getMethods () FieldgetField (String name) Annotation [] getAnnotations ()

The preceding methods have multiple overload values. You can obtain different values based on the parameter type, as shown inClass. getMethod ("info", String. class)


What can reflection do?

The preceding method is used to obtain the object attributes through reflection.

At the same time, reflection can also generate objects and methods for operating objects to form the basis of dynamic proxy and the basis of ORM.

Object Creation Method

Use the Class Object newIntance () to create a class object instance, but must have a default constructor

You can also use the constructor specified by the class object and call the newInstance method to create a specified instance.


Examples

Obtain an object and create this object to call this object method.

1 POJO class

public class User {private String userName;private String password;public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public User(){}public User(String username){this.userName=username;}

2. Call classes and Instances

Public static void main (String [] args) throws SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException, NoSuchMethodException, ClassNotFoundException {getProperty (User. class); // call} public static void getProperty (Class <?> EntityClass) throws SecurityException, NoSuchFieldException, InstantiationException, IllegalAccessException, NoSuchMethodException, ClassNotFoundException {// ----- start ---- get object ----------- String cName = entityClass. getName (); // parse the class name String userName = cName from the class name. substring (cName. lastIndexOf (". ") + 1, cName. length (); System. out. println ("entity name:" + userName); // obtain all attributes of the object Field [] fields = entityClass. getDeclaredFields (); // obtain all methods of the object. Method [] methods = entityClass. getDeclaredMethods (); List <String> listfeld = new ArrayList <> (); for (Field field: fields) {System. out. println ("attribute names:" + field. getName () ;}for (Method method: methods) {System. out. println ("method names:" + method. getName ();} // ------- get object-end -------- + // reflection create object, call object method ------- start -------- User userfroname = (User) Class. forName (cName ). newInstance (); // Method for retrieving Class objects 1: Use the string User userClass = (User) entityClass. newInstance (); // method for getting Class objects 2: using Class userClass. setUserName ("My name is: Ren qiuming --- create an object by class name"); userfroname. setUserName ("My name is: Ren qiuming -- Class type creation object"); System. out. println (userClass. getUserName (); System. out. println (userfroname. getUserName (); // reflection creates an object and calls the object method ------- end --------}

3 Test Results


Object Name: User
Property names: userName
Attribute names include: password
Method names: getUserName
Method names: setUserName
Method names: setPassword
The methods are named getPassword.
My name is: Ren qiuming --- create an object using the class name
My name is: Ren qiuming-Class Object Creation


Summary:

In general, the java reflection mechanism can solve some inflexible programs, IOC dependency injection, dynamic proxy, and dynamic over-name reflection call class methods. But at the same time, reflection also brings about efficiency issues. Everything has two sides, and flexibility is inevitable at the cost of efficiency.

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.