反射的最基本API的调用

反射思想由来已久,由于一直对java中反射的用法一直不太熟悉,特地找了一些资料学习了 一下,现在通过以下一些实例,对java中反射机制的一些用法做一些介绍:

获得实例对象的一个fieldmethodconstructor

下面是一个简单的例子:

package reflection;

import java.lang.reflect.Field;

public class GetFieldSimple {

public int height;

private int width;

public GetFieldSimple(int height, int width) {

super();

this.height = height;

this.width = width;

}

static void printHeight(GetFieldSimple gfs){

Field heigthField;

Method method;

Constructor cons;

Integer height;

Class c =gfs.getClass(); //获得运行时对象

//省略了try catch的代码

heigthField=c.getField("height"); //获得指定的字段封装为对象

height = heigthField.getInt(gfs); //从对象中取出字段值

System.out.println(height);

heigthField=c.getDeclaredField("width");//widthprivate

height = heigthField.getInt(gfs);

System.out.println(height);

method=c.getMethod("printMethodName1");

System.out.println("method name"+method.getName());

method=c.getDeclaredMethod("printMethodName2");//printMethodName2 //private

System.out.println("method name"+method.getName());

cons=c.getConstructor(new Class[] {int.class,int.class});

System.out.println("cons "+cons.getName() +" "+cons.getTypeParameters());

}

public static void main(String[] args) {

GetFieldSimple gg = new GetFieldSimple(100, 200);

printHeight(gg);

}

}

运行后会报java.lang.NoSuchFieldException: width这个错误,这是因为width是一个private类型。

c.getField(“***”)这个方法可以返回c所表示的类或接口的所有的公共字段。

c.getDeclaredField("xxxx");返回已声明的field(包括private类型)。

Method中的getMethod() 获得public方法和getDelcaredMethod()可以获得所有。

static字段可以直接从类中取而不需要从对象中取等

更详细的用法,可以去多看看API。这个只是最简单的一个例子。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值