Java中获取类的运行时结构

2021/4/14 22:29:14

本文主要是介绍Java中获取类的运行时结构,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

获取运行时类的完整结构

  • 通过反射获取运行时类的完整结构

    • Field(属性)、Method(方法)、Constructor(构造器)、Superclass(父类)、Interface(接口)、Annotation(注解)

  • 实现的全部接口

  • 所继承的父类

  • 全部的构造器

  • 全部的方法

  • 全部的Field

  • 注解

  • . . .

package com.chao.reflection;
import javax.naming.Name;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//获得类的信息
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.chao.reflection.User");
        //User user = new User();
        //c1 = user.getClass();
        //获得类的名字
        System.out.println(c1.getName()); //获得包名 + 类名
        System.out.println(c1.getSimpleName());//获得类名
        //获得类的属性
        System.out.println("========================");
        Field[] fields = c1.getFields(); //只能找到public属性

        fields = c1.getDeclaredFields();//找到全部的属性
        for (Field field : fields) {
            System.out.println(field);
        }
        //获得指定属性的值
        Field name = c1.getDeclaredField("name");
        System.out.println(name);
        //获得类的方法
        System.out.println("========================");
        Method[] methods = c1.getMethods();
        for (Method method : methods) {
            System.out.println("正常的:"+method);//获得本类及其父类的全部public方法
        }
        methods = c1.getDeclaredMethods();//获得本类的所有方法
        for (Method method : methods) {
            System.out.println("getDeclaredMethods:"+method);
        }
        //获得指定方法
        //重载
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);
        //获得指定的构造器
        System.out.println("========================");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("#" + constructor);
        }
        //获得指定的构造器
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        System.out.println("指定:"+declaredConstructor);
    }
}

小结:

  • 在实际的操作过程中,取得类的信息的操作代码,并不会经常开发。

  • 一定要熟悉java.lang.reflect包的作用,反射机制。

  • 如何取得属性、方法、构造器的名称,修饰符等。



这篇关于Java中获取类的运行时结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程