Java Learning Summary (14)--java reflection mechanism, using reflection to dynamically create objects

Source: Internet
Author: User
Tags modifier reflection

A Java Reflection mechanism
1. What is reflection: Reflection is a Java object that refers to various elements in a Java class. Example: A class has: member variables, methods, construction methods, and so on, the use of reflection technology can be used to analyze a class, each component is mapped into a single object.
2.Java Reflection Common classes:
(1) class-can get member information for classes and classes
(2) Field class-Accessibility to the properties of a class
(3) Method-method of callable class
(4) How to construct constructor-callable class
3. How to use reflection (basic steps):
(1) Import java.lang.reflect.*
(2) Get the Java.lang.Class object for the class that needs to be manipulated
(3) Call the class method to get objects such as Field,method
(4) Operations using the Reflection API (setting properties, calling methods)
4.Class class:
(1) class is the origin and entry of the Java reflection mechanism
(2) Class instantiation object represents a running Java class or interface
• Each class has its own class object
• Used to obtain various information related to the class
• Provides methods for obtaining information about the class
· Class class inherits to Object
(3) Class class storage structure information
• class name; • parent class, interface; • Methods, construction methods, properties; • annotations
5. Three ways to get class objects:
(1) Method one:
Method 1: Object. GetClass ()
Student stu=new Student ();
Class Clazz=stu.getclass ();
(2) Method two:
Method 2: Classes. Class
Class clazz= Student.class;
Class Clazz=string.class;
Method Three:
Method 3:class.forname ()
Clazz=class.forname ("java.lang.String");
Clazz=class.forname ("Java.util.Date");
Example (code):
Student Information Class (bean)
Package org.reflect.Class;

public class Student {
private String name;
private int age;
private double score;

public Student() {}public Student(String name, int age, double score) {    this.name = name;    this.age = age;    this.score = score;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}public int getAge() {    return age;}public void setAge(int age) {    this.age = age;}public double getScore() {    return score;}public void setScore(double score) {    this.score = score;}

public void Learn () {
System.out.println (this.name + "learning ..."); br/>}
@Override

Return "Student [name=" + name + ", age=" + Age + ", score=" + Score

    • "]";
      }

}

Get class class object Test classes
Package org.reflect.Class;

Import Java.lang.reflect.Modifier;
public class Classdemo {

public static void main(String[] args) {    Student stu=new Student();    Class<?> c1=stu.getClass();//方式一    Class<Student> c2= Student.class;//方式二    Class<?> c3=null;    try {        c3=Class.forName("org.reflect.Class.Student");   // 方式三    } catch (ClassNotFoundException e) {        e.printStackTrace();    }    System.out.println("方式一获取的Class对象为:"+c1.getSimpleName());    System.out.println("方式二获取的Class对象为:"+c2);    System.out.println("方式三获取的Class对象为:"+c3);    int mod=c1.getModifiers();//获取修饰符所对应的整数    String modifier=Modifier.toString(mod);//获取修饰符    System.out.println(c1+"类所用的修饰符为:"+modifier);}

}

Operation Result:
Mode one gets the class object: Student
Mode two get class object: Reflect.student
Way three get class object: Reflect.student
Modifiers for the Student class: public
6. Get the structure information of a class using class classes
(1) Get class object:

(2) Get filed object

(3) Get Method object

(4) Get constructor object

Code samples (examples are based on the student class above)
Example 1 (Get filed object)
Package org.reflect.Filed;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Modifier;
public class Fileddemo {

public static void main(String[] args) {    Class<Student> cl=Student.class;//获取代表Student类的Class对象    Field[] fields=cl.getDeclaredFields();//获取属性对象,返回数组    System.out.println(cl.getSimpleName()+"类中声明的属性有:");    for(Field f:fields){        String filedName=f.getName();//获取属性名        Class<?> filedType=f.getType();//获取属性类型        int mod=f.getModifiers();//获取修饰符对应整数        String modifier=Modifier.toString(mod);//获取修饰符        System.out.println(modifier+" "+filedType.getSimpleName()+" "+filedName);    }}

}

Operation Result:
The attributes declared in the Student class are:
Private String Name
private int Age
Private Double Score
Example 2 (Get Method Object)
Package method;

Import Java.lang.reflect.Method;
Import Java.lang.reflect.Modifier;

public class Methoddemo {

public static void Main (string[] args) {try {class<?> Cls=class.forname ("method.        Student ");        Method[] Methods=cls.getdeclaredmethods ();   for (Method method:methods) {String methodname=method.getname ();  Gets the method name Class<?> Returntype=method.getreturntype ();   Gets the return value type of the method String modstr=modifier.tostring (Method.getmodifiers ());   Gets the modifier of the method class<?>[] Paramtypes=method.getparametertypes ();            Gets the parameter type System.out.print (modstr+ "" +returntype.getsimplename () + "" +methodname+ "(");            if (paramtypes.length==0) {System.out.print (")");                    } for (int i=0;i<paramtypes.length;i++) {//traversal form parameter type if (i==paramtypes.length-1) {                System.out.print (Paramtypes[i].getsimplename () + "args" +i+ ")");                }else{System.out.print (Paramtypes[i].getsimplename () + "args" +i+ ",");            }            }System.out.println ();    }} catch (Exception e) {e.printstacktrace (); }}

}

Operation Result:
public void Eat (String args0,string args1)
public int Getage ()
public void setage (int args0)
Public double Getscore ()
public void SetScore (double args0)

7. Creating objects dynamically using reflection
(1) Method one:
Use class's Newinstance () method, only for parameterless construction methods

(2) Method two:
Method Two: Call Constructor's Newinstance () method, applicable to all construction methods

Example 3 (Get constructor object)
Package org.reflect.Constructor;

Import Java.lang.reflect.Constructor;

public class Constructordemo {

public static void main(String[] args) {    Class<Student> cl=Student.class;//获取Class对象,代表Student类    try {        Constructor<Student> con=cl.getDeclaredConstructor(String.class,int.class,double.class);//获取散参构造方法        Student stu=con.newInstance("张无忌",23,96.7);        System.out.println(stu);    } catch (Exception e) {        e.printStackTrace();    } }

}
Operation Result:
Student [name= Zhang Mowgli, age=23, score=96.7]
Example 4 (Dynamic creation method):
Package method;

Import Java.lang.reflect.Method;

public class InvokeMethod {

public static void main(String[] args) {    Class<Student> cls=Student.class;    try {        Student stu=cls.newInstance();   // 通过反射机制实例化对象,使用此newInstance()方法,要求类中必须包含一个无参构造方法        Method setNameMethod=cls.getMethod("setName",String.class);        setNameMethod.invoke(stu,"风清扬");   // 使用stu对象调用setName(String name)方法,传入"风清扬"参数        Method getNameMethod=cls.getMethod("getName");        System.out.println(getNameMethod.invoke(stu));  // 使用stu对象调用getName()方法,返回一个值    } catch (Exception e) {        e.printStackTrace();    } }

}
Operation Result:
Wind

Java Learning Summary (14)--java reflection mechanism, using reflection to dynamically create objects

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.