Java Reflection Series--Method Encyclopedia

Original URL: Java Reflection Series--Method Encyclopedia

Introduction

        This article introduces methods related to Java reflection.

Class-related methods

method

illustrate

getName()

Returns the name of this class as a String.

newInstance()

According to a Class object, an instance of its corresponding class is generated, which calls the default constructor of this class (no default parameterless constructor will report an error)

getClassLoader()

Returns the class loader of the class corresponding to this Class object.

getSuperClass()

Returns the Class object corresponding to the direct parent class corresponding to a subclass

getComponentType()

If the current class represents an array, returns a Class object representing the array's components, otherwise returns null.

getConstructor(Class[])

Returns the specified public constructor object for the class represented by the current Class object.

getConstructors()

Returns an array of all public constructor objects of the class represented by the current Class object.

getDeclaredConstructor(Class[])

Returns a constructor object specified by the class represented by the current Class object.

getDeclaredConstructors()

Returns an array of all declared constructor objects of the class represented by the current Class object.

getDeclaredField(String)

Returns a domain object specifying the class or interface represented by the current Class object.

(Get a specified public field, including inherited ones)

getDeclaredFields()

Returns an array of all declared domain objects for the class or interface represented by the current Class object.

(Get public and private properties (private, public, protected, regardless of access rights), excluding inheritance ).

getDeclaredMethod(String, Class[])

Returns a method object specified by the class or interface represented by the current Class object.

getDeclaredMethods()

Returns an array of all declared methods of the class or interface represented by the Class object.

getField(String)

Returns the specified public field object of the class or interface represented by the current Class object.

(Get the specified public fields, including inherited ones)

getFields()

Returns an array of all accessible public domain objects of the class or interface represented by the current Class object.

(You can get self and inherited public properties)

(You can get public properties (public), including inheritance ).

getInterfaces()

Returns the interface implemented by the class or interface represented by the current object.

getMethod(String, Class[])

Returns the specified public member method object of the class or interface represented by the current Class object.

getMethods()

Returns an object array of all public member methods of the class or interface represented by the current Class object, including the methods declared and inherited from parent classes.

isArray()

Determine whether this Class object corresponds to an array object

isInstance(Object)

This method is the dynamic equivalent of the Java language instanceof operation.

isInterface()

Determines whether the specified Class object represents an interface type

isPrimitive()

Determines whether the specified Class object represents a Java base type.

Get Interface/Parent Class/Constructor

method illustrate
Class<?>[] c1 = c.getInterfaces(); Get the implemented interface
Class<?> c2 = c.getSuperclass(); get parent class
Constructor<?> con[] = c.getConstructors(); get constructor

get method data

method

illustrate

Method getMethod(String name, Class<?>... parameterTypes)

Get method by method name and parameter list

Method[] getMethods()

Get all methods.

反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共(public) member 方法。

Method getDeclaredMethod(String name, Class<?>... parameterTypes)

Method[] getDeclaredMethods()

反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。 

详细方法

方法

说明

int getModifiers()

取得本方法的访问修饰符。

取得后通过Modefier.toString(xxx)还原

String getName()

取得方法的名称

Class<?>[] getParameterTypes()

得到方法的全部参数类型

Class<?> getReturnType()

得到方法的返回值类型

CIass<?>[] getExceptionType()

得到一个方法的全部抛出异常

实例

package org.example.a;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

interface ICategory {
    public static final String CATEGORY_NAME = "Human";

    public void sayCategory();

    public String sayHello(String name, Integer age);
}

class Human implements ICategory {
    private String name;
    private Integer age;

    public Human() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public void sayCategory() {
        System.out.println(CATEGORY_NAME);
    }

    @Override
    public String sayHello(String name, Integer age) {
        return "名字:" + name + "年龄:" + age;
    }
}

public class Demo {
    public static void main(String[] args) {
        Class<?> c = null;
        try {
            c = Class.forName("org.example.a.Human");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Method m[] = c.getMethods();
        for (int i = 0; i < m.length; i++) {
            Class<?> r = m[i].getReturnType();
            Class<?> p[] = m[i].getParameterTypes();
            int xx = m[i].getModifiers();
            System.out.print(Modifier.toString(xx) + " ");
            System.out.print(r.getName() + " ");
            System.out.print(m[i].getName());
            System.out.print("(");
            for (int x = 0; x < p.length; x++) {
                System.out.print(p[x].getName() + " " + "arg" + x);
                if (x < p.length - 1) {
                    System.out.print(", ");
                }
            }
            System.out.print(")");

            Class<?> ex[] = m[i].getExceptionTypes();
            if (ex.length > 0) {
                System.out.print(" throws ");
                for (int j = 0; j < ex.length; j++) {
                    System.out.print(ex[j].getName());
                    if (j < ex.length - 1) {
                        System.out.print(",");
                    }
                }
            }
            System.out.println();
        }
    }
}

执行结果

public java.lang.String getName()
public void setName(java.lang.String arg0)
public java.lang.String sayHello(java.lang.String arg0, java.lang.Integer arg1)
public java.lang.Integer getAge()
public void setAge(java.lang.Integer arg0)
public void sayCategory()
public final void wait() throws java.lang.InterruptedException
public final void wait(long arg0, int arg1) throws java.lang.InterruptedException
public final native void wait(long arg0) throws java.lang.InterruptedException
public boolean equals(java.lang.Object arg0)
public java.lang.String toString()
public native int hashCode()
public final native java.lang.Class getClass()
public final native void notify()
public final native void notifyAll()

获取属性

方法

说明

Field getField(String name)

根据属性名称获取public属性

Field[] getFields()

获得该类所有的public属性

Field getDeclaredField(String name)

根据属性名称获取属性。private属性也可获取

Field[] getDeclaredFields()

获得该类所有的属性。private属性也可获取

详细方法

方法

说明

Object get(Object obj)

获得一个对象中属性的具体内容

void set(Object obj,Object value)

设置指定对象中属性的具体内容

int RetModifiers()

获得属性的修饰符

String getName()

获得此属性的名称

boolean isAccessible()

判断此属性是否可被外部访问

void setAccessible(boolean flag)

设置一个属性是否可被外部访问

static void setAccessibie(AccessibIeObject[] array,boolean flag)

Sets whether a set of properties can be accessed externally

String toString()

Returns information about this Field class

example

package org.example.a;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

interface ICategory {
    public static final String CATEGORY_NAME = "Human";

    public void sayCategory();

    public String sayHello(String name, Integer age);
}

class Human implements ICategory {
    private String name;
    private Integer age;

    public Human() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }


    @Override
    public void sayCategory() {
        System.out.println(CATEGORY_NAME);
    }

    @Override
    public String sayHello(String name, Integer age) {
        return "名字:" + name + "年龄:" + age;
    }
}

public class Demo {
    public static void main(String[] args) {
        Class<?> c = null;
        try {
            c = Class.forName("org.example.a.Human");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Field f[] = c.getDeclaredFields();
        System.out.println("本类属性: ");
        for (int i = 0; i < f.length; i++) {
            Class<?> r = f[i].getType();
            int mo = f[i].getModifiers();
            String priv = Modifier.toString(mo);
            System.out.print(priv + " ");
            System.out.print(r.getName() + " ");
            System.out.print(f[i].getName());
            System.out.println(";");
        }

        System.out.println("-------------------------------------------");

        Field f1[] = c.getDeclaredFields();
        System.out.println("公共属性: ");
        for (int i = 0; i < f1.length; i++) {
            Class<?> r = f1[i].getType();
            int mo = f1[i].getModifiers();
            String priv = Modifier.toString(mo);
            System.out.print(priv + "");
            System.out.print(r.getName() + " ");
            System.out.print(f1[i].getName());
            System.out.println(";");
        }
    }
}

Results of the

本类属性: 
private java.lang.String name;
private java.lang.Integer age;
-------------------------------------------
公共属性: 
privatejava.lang.String name;
privatejava.lang.Integer age;

get annotation

        Method, Constructor, and Field objects can all determine whether there is a specific annotation class. The method is: boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)

example

An example of an enumeration class is used here, and the general class is similar.

package org.example.a;

import java.lang.reflect.Field;

enum Color{
    @Deprecated
    RED,

    GREEN,
    BLUE
}

public class Demo {
    public static void main(String[] args) {
        for (Color value : Color.values()) {
            Field field = null;
            try {
                field = Color.class.getField(value.name());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            if (field.isAnnotationPresent(Deprecated.class)) {
                System.out.println(value.name() + "上有注解类:" + Deprecated.class.getName());
            }
        }
    }
}

Results of the

RED上有注解类:java.lang.Deprecated 

Operate array

method illustrate
Class<?> getComponentType() Get an array of Class objects

detailed method

method illustrate
static Object get(Object array,int index) Get the content of the array according to the subscript
static Object newlnstance(Class<?> componentType, int length) Create a new array object based on the existing array type
static void set(Object array,int index,Object value) Modify the content of the specified location

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/126878437