Home > Java > javaTutorial > Things to note about the reflection mechanism in Java

Things to note about the reflection mechanism in Java

黄舟
Release: 2017-09-21 09:51:23
Original
1649 people have browsed it

This article mainly introduces the relevant content of Java reflection mechanism, involving dynamic loading of class classes, obtaining member variables, constructor information and other information. Friends in need can refer to it.

Everyone knows that in order for a Java program to run, the Java class must be loaded by the Java virtual machine. Java classes cannot run normally if they are not loaded by the Java virtual machine. Now all the programs we run know that the class you need has been loaded during compilation.

Java's reflection mechanism is not sure which class is loaded during compilation, but is loaded, detected, and self-examined when the program is running. Use classes that are not known at compile time. Such a feature is reflection.

The reflection mechanism is that in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic acquisition The information and the function of dynamically calling the object's methods are called the reflection mechanism of the Java language.

This article will introduce the knowledge of reflection from the following aspects:

Calss usage method reflection constructor reflection member variable reflection

1. What is a class class

In the object-oriented world, everything is an object. Classes are objects, and classes are instance objects of the java.lang.Class class. In addition, the class class can only be new by the Java virtual machine. Any class is an instance object of the Class class. This instance object has three expressions:


public class User{
} 
public class ClassTest{
User u=new User();
 //方式1:
 Class c1=User.class;
//方式2:
Class c2=u.getClass();
//方式3:
Class c3=Class.forName("com.forezp.User");
 
//可以通过类的类型创建该类的实例对象
User user=(User)c1.newInstance();
}
Copy after login

2. Dynamic loading of class class

Class.forName( The full name of the class); this method not only represents the type of the class, but also represents the dynamically loaded class. Classes loaded at compile time are statically loaded, and classes loaded at runtime are dynamically loaded.

3. Obtain method information

Basic data types and void keywords are instances of the Class class; you can use get
ame ();getSimpleName() gets the name of the class.


Class c1=String.class;
Class c2=int.class;
Class c3=void.class;
System.out.println(c1.getName());
System.out.println(c2.getSimpleName());
Copy after login

Get all the methods of the class and print them out:


public static void printClassInfo(Object object){
  Class c=object.getClass();
  System.out.println("类的名称:"+c.getName());
  /**
   * 一个成员方法就是一个method对象
   * getMethod()所有的 public方法,包括父类继承的 public
   * getDeclaredMethods()获取该类所有的方法,包括private ,但不包括继承的方法。
   */
  Method[] methods=c.getMethods();//获取方法
  //获取所以的方法,包括private ,c.getDeclaredMethods();
  for(int i=0;i<methods.length;i++){ parametertypes="methods[i].getParameterTypes();" pre="" returntype="methods[i].getReturnType();"></methods.length;i++){>
Copy after login


public class ReflectTest {
  public static void main(String[] args){
    String s="ss";
    ClassUtil.printClassInfo(s);
  }
}
Copy after login

Run:


类的名称:java.lang.String
booleanequals(java.lang.Object,)
java.lang.StringtoString()
inthashCode()
…
Copy after login

4. Get the member variable information

You can also get the member variable information of the class


public static void printFiledInfo(Object o){
  Class c=o.getClass();
  /**
  * getFileds()获取public
  * getDeclaredFields()获取所有
  */
  Field[] fileds=c.getDeclaredFields();
  for(Field f:fileds){
   //获取成员变量的类型
   Class filedType=f.getType();
   System.out.println(filedType.getName()+" "+f.getName());
  }
 }
Copy after login


public static void main(String[] args){
    String s="ss";
    //ClassUtil.printClassInfo(s);
    ClassUtil.printFiledInfo(s);
  }
Copy after login

Run:


[C value 
int hash 
long serialVersionUID 
[Ljava.io.ObjectStreamField; serialPersistentFields 
java.util.Comparator CASE_INSENSITIVE_ORDER 
int HASHING_SEED 
int hash32
Copy after login

5. Obtain Constructor information


public static void printConstructInfo(Object o){
  Class c=o.getClass();
  Constructor[] constructors=c.getDeclaredConstructors();
  for (Constructor con:constructors){
   System.out.print(con.getName()+"(");
   Class[] typeParas=con.getParameterTypes();
   for (Class class1:typeParas){
    System.out.print(class1.getName()+" ,");
   }
   System.out.println(")");
  }
 }
Copy after login


public static void main(String[] args){
    String s="ss";
    //ClassUtil.printClassInfo(s);
    //ClassUtil.printFiledInfo(s);
    ClassUtil.printConstructInfo(s);
  }
Copy after login

Run:


java.lang.String([B ,) 
java.lang.String([B ,int ,int ,) 
java.lang.String([B ,java.nio.charset.Charset ,) 
java.lang.String([B ,java.lang.String ,) 
java.lang.String([B ,int ,int ,java.nio.charset.Charset ,) 
java.lang.String(int ,int ,[C ,) 
java.lang.String([C ,boolean ,) 
java.lang.String(java.lang.StringBuilder ,) 
java.lang.String(java.lang.StringBuffer ,)
…
Copy after login

6. Operation of method reflection

Get a method: You need to get the name of the method and the parameters of the method to determine a method.

Reflection operation of method:


method.invoke(对象,参数列表);
Copy after login

For example:


class A{
 public void add(int a,int b){
  System.out.print(a+b);
 }
 public void toUpper(String a){
  System.out.print(a.toUpperCase());
 }
}
Copy after login


public static void main(String[] args) {
  A a=new A();
  Class c=a.getClass();
  try {
   Method method=c.getMethod("add",new Class[]{int.class,int.class});
   //也可以 Method method=c.getMethod("add",int.class,int.class);
   //方法的反射操作
   method.invoke(a,10,10);
  }catch (Exception e){
   e.printStackTrace();
  }
 }
Copy after login

Run:


20
Copy after login

This article has explained the basic usage of java reflection, which can determine the ownership of any object at runtime class; construct an object of any class at runtime; determine the member variables and methods of any class at runtime; call the method of any object at runtime; generate a dynamic proxy.

The above is the detailed content of Things to note about the reflection mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template