Java反射的基本操作

最近重新复习了Java反射,记录如下。
通过反射获取类的基本信息:
获取类的构造函数:

public static void getConstructors(Object obj) {
        Class class1 = obj.getClass();
        //get class1's constructors
        Constructor[] constructors = class1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            String cName = constructor.getName();
            System.out.print(cName+"(");
            Class[] parameterTypes = constructor.getParameterTypes();
            for (Class type : parameterTypes) {
                System.out.print(type.getName()+",");
            }
            System.out.println(")");
        }
    }
        //测试代码:
        ReflactDemo.getConstructors(new Integer(1));
        System.out.println("-----");
        ReflactDemo.getConstructors("test");

测试结果:

这里写图片描述

获取类的属性

public static void getFields(Object obj) {
        Class class1 = obj.getClass();
        //get class1's members
        Field[] fields = class1.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            String fieldType = field.getType().getSimpleName();
            System.out.println(fieldType + " " + fieldName);
        }
    }
//测试代码
class TestClass1{
    public String name = "bear";
    public int age = 18;
    public float power = (float) 10.6;

    public TestClass1() {
        this.name = "bear2";
    }

    public void print()
    {
        System.out.println(name+" "+age+" "+power);
    }
}


ReflactDemo.getFields(new TestClass1());

这里写图片描述
获取类的方法:

public static void getMethods(Object object) {
        Class class1 = object.getClass();
        //get class1's methods;
        Method[] methods = class1.getDeclaredMethods();
        for (Method method : methods) {
            Type returnType = method.getGenericReturnType();
            System.out.print(returnType+" ");
            System.out.print(method.getName()+"(");
            Class[] types = method.getParameterTypes();
            for (Class type : types) {
                System.out.print(type.getName()+",");
            }
            System.out.println(")");
        }
    }
    //测试代码:
    ReflactDemo.getMethods("klajs");

这里写图片描述

调用类的方法:

try {
            Class class1 = Class.forName("com.bear.TestClass1");
            Method method = class1.getMethod("print", new Class[]{});
            method.invoke(class1.newInstance());

        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值