search
HomeJavajavaTutorialDetailed introduction to Java reflection to obtain class and object information

Reflection can solve the problem that it is impossible to predict at compile time which objectand class it belongs to, and the information of the object and class can only be known based on the information when the program is running.

When two people collaborate on development, you only need to know the other party's class name to carry out preliminary development.

Get the class object

  • Class.forName(String clazzName) static method

  • Call the class attribute of the class, Person. class returns the Person class object (recommended)

  • Call the getClass() method of an object

Specific use You still have to choose based on actual conditions. The first method is relatively free. You only need to know a class name. It will not verify whether the class exists. The second and third methods will verify whether the class exists.

Get class information

Get class constructor

  • ##Connstructor getConstructor(Class>.. .parameterTypes): Returns the public constructor with specified formal parameters of the corresponding class of this Class object

  • Constructor>[] getConstructors() :Return all public constructors of the class corresponding to this Class object

  • ##Constructor[] getDeclaredConstructor(Class>...parameterTypes)

    :Return This class object corresponds to the constructor of the class with specified parameters, regardless of the access permission of the constructor

  • ##Constructor>[] getDeclaredConstructors()
  • : Return This class object corresponds to all constructors of the class, regardless of the access rights of the constructor

    Get the class member method

    Method getMethod (String name,Class>...parameterTypes)
  • : Returns the public method with specified formal parameters of the corresponding class of this class object

  • Method[] getMethods()
  • : Returns all public methods of the class represented by this class object

    ##Method getDeclaredMethod(string name,Class>...parameterTypes)
  • : Returns the method with specified formal parameters of the corresponding class of this class object, regardless of method access permissions
  • Method[] getDeclaredMethods()
  • : Returns this The class object corresponds to all methods of the class, regardless of the access rights of the method
  • Get the class member variables

Field getField(String name )
    : Returns the public member variable of the specified name corresponding to this class object
  • Field[] getFields()
  • : Returns the public member variable of the specified class corresponding to this class object All public member variables
  • Field getDeclaredField(String name)
  • : Returns the member variable with the specified name corresponding to this class object, regardless of member variable access permissions
  • Field[] getDeclaredFields()
  • : Returns all member variables of the class corresponding to this class object, regardless of the access rights of the member variables
  • Get class annotation

##A getAnnotation(ClassannotationClass)

: Try to get the corresponding class of the class object Annotation of the specified type. If the type annotation does not exist, null is returned

Get the external class where the object of this class is located

  • Class> getDeclaringClass(): Returns the external class where the corresponding class of the Class object is located

Gets the interface implemented by the corresponding class of the class object

  • Class>[] getInterfaces(): Returns all interfaces implemented by the corresponding class of the Class object

Get the parent class inherited by the corresponding class of this class object

  • ##Class super T> getSuperclass(): Return the The Class object of the super class corresponding to the Class object

Get the basic information such as the modifier, package, class name, etc. of the class object corresponding to the class

  • int getModifiers(): Returns all modifiers of this class or interface. The modifiers are composed of public, protected, private, final, static, abstract and other corresponding constants. The returned integerYou should use the method of the Modifier tool class to decode to get the real modifier

  • Package getPackage(): Get the package of this class

  • String getName(): Returns the short name of the class represented by this CLass object in the form of string

Determine whether the class is an interface, enumeration, or annotation type

  • boolean isAnnotation(): Returns whether this class object represents an annotation type

  • boolean isAnnotationPresent(Class extends Annotation>annotationClass): Determine whether this Class object is decorated with class Annotation

  • boolean isAnonymousClass(): Returns whether this class object is an anonymous class

  • ##boolean isArray()

    : Returns this class object Whether it represents an arrayclass

  • boolean isEnum()

    : Returns whether this class object represents an enumeration

  • boolean isInterface()

    : Returns whether this class object represents an interface

  • ##boolean isInstance(
  • Object

    obj ): Determine whether obj is an instance of this class object. This method can completely replace the instanceof<a href="http://www.php.cn/wiki/60.html" target="_blank"> operator</a>

    public interface Colorable {
         public void value();
    }
    public class ClassInfo {
    
        public static void main(String[] args) throws NoSuchMethodException, SecurityException {
            Class<Colorable> cls=Colorable.class;
            System.out.println(cls.getMethod("value"));
            System.out.println(cls.isAnnotation());
            System.out.println(cls.isInterface());
        }
    
    }

  • result

public abstract void com.em.Colorable.value()
false
true
New method parameter reflection in Java8

    int getParameterCount()
  • : Get the number of formal parameters of the constructor or method

  • Parameter[] getParameters()
  • : Get all formal parameters of the constructor or method

  • getModifiers( )
  • : Get the modifier that modifies the formal parameter

  • String getName()
  • : Get the formal parameter name

  • Type getParameterizedType()
  • : Get the formal parameter type with generics

  • Class>getType()
  • : Get the formal parameter type Parameter type

  • boolean isNamePresent()
  • : This method returns whether the class file of the class contains the formal parameter name information of the method

  • boolean isVarArgs()
  • : This method is used to determine whether the parameter is a variable number of formal parameters

    public class Test {
        public void getInfo(String str,List<String>list){
            System.out.println("成功");
        }
    }
    public class ClassInfo {
    
        public static void main(String[] args) throws NoSuchMethodException, SecurityException {
            Class<Test> cls=Test.class;
            Method med=cls.getMethod("getInfo", String.class,List.class);
            System.out.println(med.getParameterCount());
            Parameter[] params=med.getParameters();
            System.out.println(params.length);
            for(Parameter par:params){
                System.out.println(par.getName());
                System.out.println(par.getType());
                System.out.println(par.getParameterizedType());
            }
        }
    
    }

  • Result

2
2
arg0
class java.lang.String
class java.lang.String
arg1
interface java.util.List
java.util.List<java.lang.String>
Reflection generated object

Use the newInstance() method of the Class object to create an instance of the Class object. This method requires a default constructor (more commonly used)
  • First use the Class object to obtain the specified Constructor object, and then call the newInstance() method of the Constructor object to create an instance of the corresponding class of the Class object
  • Reflection calling method

    Object invoke(Object obj,Object...args)
  • : obj in this method is the main call to execute the method, followed by The args are the actual parameters passed into the method when executing the method

    public class Test {
    
        public Test(String str) {
            System.out.println(str);
        }
        public void getInfo(String str){
            System.out.println(str);
        }
    }
    public class ClassInfo {
    
        public static void main(String[] args) throws Exception {
            Class<Test> cls=Test.class;
            Constructor<Test>construct=cls.getConstructor(String.class);
            Test test=construct.newInstance("初始化");
            Method med=cls.getMethod("getInfo", String.class);
            med.invoke(test, "调用方法成功");
        }
    
    }

  • Result

初始化
调用方法成功
Next, the official will take a closer look at the chestnut below
public class Test {

    public Test(String str) {
        System.out.println(str);
    }
    //私有方法
    private void getInfo(String str){
        System.out.println(str);
    }
}
public class ClassInfo {

    public static void main(String[] args) throws Exception {
        Class<Test> cls=Test.class;
        Constructor<Test>construct=cls.getConstructor(String.class);
        Test test=construct.newInstance("初始化");
      //为啥使用这个方法呢?
        Method med=cls.getDeclaredMethod("getInfo", String.class);
      //为啥使用这个方法呢?
        med.setAccessible(true);
        med.invoke(test, "调用方法成功");
    }

}

Result

初始化
调用方法成功
setAccessible(boolean flag): Set the value to true, indicating that the Java language access permission check should be canceled when using this Method

Accessing member variable values

    getXxx(Object obj)
  • : Get the value of the member variable of the obj object. Xxx here corresponds to 8 basic types. If the type of the member variable is

    reference type, remove the Xxx part

  • setXxx(Object obj ,Xxx val)
  • : Set the member variable of the obj object to the val value. The Xxx here corresponds to the 8 basic types. If the type of the member variable is a reference type, cancel the Xxx after set

  • The above two methods can access all members Variables, including private private member variables
public class Test {
    private int num;

    public Test(String str) {
        System.out.println(str);
    }
    private void getInfo(String str){
        System.out.println(str);
    }
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }

}
public class ClassInfo {

    public static void main(String[] args) throws Exception {
        Class<Test> cls=Test.class;
        Constructor<Test>construct=cls.getConstructor(String.class);
        Test test=construct.newInstance("初始化");
        Method med=cls.getDeclaredMethod("getInfo", String.class);
        med.setAccessible(true);
        med.invoke(test, "调用方法成功");
        Field fld=cls.getDeclaredField("num");
        fld.setAccessible(true);
        fld.setInt(test, 12);
        System.out.println(fld.getInt(test));
    }

}

Result

初始化
调用方法成功
12
Operation array

There is an Array under the java.lang.reflect package Class, which can dynamically create arrays

static Object newInstance(Class>componentType,int...length)

: Create a new array with the specified element type and specified dimensions

static xxx getXxx(Object array,int index):返回array数组中第index个元素。其中xxx是各种基本数据类型,如果数组元素是引用类型,则该方法变为get()

static void setXxx(Object array,int index,xxx val):将array数组中低index 个元素的值设为val,其中xxx是各种基本数据类型,如果数组元素是引用类型,则该方法变为set()

public class ArrayInfo {

    public static void main(String[] args) {
        Object arrays=Array.newInstance(String.class, 3);
        Array.set(arrays, 0, "第一个");
        Array.set(arrays, 1, "第二个");
        Array.set(arrays, 2, "第三个");
        System.out.println(Array.get(arrays, 2));
    }
}

The above is the detailed content of Detailed introduction to Java reflection to obtain class and object information. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

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

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

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

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

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

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

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

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

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

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

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

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

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

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools