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. [Translated from official documents]
This article will introduce the knowledge of reflection from the following aspects:
class Use
Reflection of method
MemberReflection of variables
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(); }
2. Dynamic loading of class class
Class.forName (full name of the class); This method not only represents the type of the class, but also represents the dynamic Load class. Classes loaded at compile time are static loaded, and classes loaded at runtime are dynamically loaded.
3. Obtaining method information
Basic data types, void keywords are instances of the Class class; the name of the class can be obtained through getame();getSimpleName() .
Class c1=String.class; Class c2=int.class; Class c3=void.class; System.out.println(c1.getName()); System.out.println(c2.getSimpleName());
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++){ //得到方法的返回类型 Class returnType=methods[i].getReturnType(); System.out.print(returnType.getName()); //得到方法名: System.out.print(methods[i].getName()+"("); Class[] parameterTypes=methods[i].getParameterTypes(); for(Class class1:parameterTypes){ System.out.print(class1.getName()+","); } System.out.println(")"); } }
public class ReflectTest { public static void main(String[] args){ String s="ss"; ClassUtil.printClassInfo(s); } }
Run:
类的名称:java.lang.String booleanequals(java.lang.Object,) java.lang.StringtoString() inthashCode() …
4. Get the information of member variables
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()); } }
public static void main(String[] args){ String s="ss"; //ClassUtil.printClassInfo(s); ClassUtil.printFiledInfo(s); }
Run:
[C value int hash long serialVersionUID [Ljava.io.ObjectStreamField; serialPersistentFields java.util.Comparator CASE_INSENSITIVE_ORDER int HASHING_SEED int hash32
5. Get the 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(“)”); } }
public static void main(String[] args){ String s="ss"; //ClassUtil.printClassInfo(s); //ClassUtil.printFiledInfo(s); ClassUtil.printConstructInfo(s); }
Run:
java.lang.String([B ,) java.lang.String([B ,int ,int ,) java.lang.String([B ,java.nio.char set .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 ,)
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(对象,参数列表);
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()); } }
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(); } }
Run:
20
The above is the detailed content of Detailed introduction to Java reflection mechanism knowledge summary. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools
