趣讲 java反射之创建运行时类的对象

可以通过反射,获取运行时类的完整结构
Field、Method、Constructor、Superclass、interface、Annotation

具体来说可以是:
实现类的全部接口
所继承的父类
全部的构造器
全部的方法
全部的Field
注解

package com.company;

import sun.plugin2.message.GetNameSpaceMessage;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//获取类的信息
public class test07 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.company.User");

        //获得类的名字
        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");   //name是私有的,所以只能通过getDeclaredField来获得
        System.out.println(name);

        //获得类的方法
        System.out.println("========================");
        Method[] methods = c1.getMethods(); //获得本类以及父类的所有方法,只是public方法
        for (Method method : methods) {
            System.out.println("正常的:" + method);
        }

        methods = c1.getDeclaredMethods();  //获得本类的所有方法,包括私有的方法
        for (Method method : methods) {
            System.out.println("getDeclaredMethod:" + 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();  //获得本类的public方法
        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);
    }
}

输出结果是:
在这里插入图片描述
在这里插入图片描述
注释已经写得很清楚了,可以跟着玩一下~

猜你喜欢

转载自blog.csdn.net/weixin_45806131/article/details/107969204
今日推荐