java反射实例

Method add=clazz.getMethod("add", new Class[]{Integer.class,Integer.class});

add.invoke(o, new Object[]{new Integer(1),new Integer(1)});

 

Field i=clazz.getDeclaredField("i");//对私有的处理

i.setAccessible(true);//对私有的处理

i.get(o);

i.set(o, 2);

 

 

 

 

 

//Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,

  //如果参数为基本类型数据,必须转换为相应的包装类型的对象。

  //invoke()方法的返回值总是对象,
  //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,

class MyClass{

private Integer i = 12;

public static String s = "ss";

private String s1 = "";

private double d = 2.3;

 

public MyClass() {

 

}

 

public MyClass(String s1, Double d) {

this.s1 = s1;

this.d = d;

}

 

public int add(Integer numberA, Integer numberB) {

return numberA + numberB;

}

 

public static String addString(String s1, String s2) {

return s2 + "_" + s1;

}

}

 

public class Test {

 

public static void main(String args[]) throws ClassNotFoundException, SecurityException, NoSuchFieldException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{

Class clazz = MyClass.class;

//Class clazz=实例.getClass();

//Class clazz=Class("包名.类名");

 

//静属性方法

//获得

Field static_s=clazz.getField("s");

Method static_addString=clazz.getMethod("addString", new Class[]{String.class,String.class});

//使用

static_s.set(null, "aa");

static_s.get(null);

 

static_addString.invoke(null, new Object[]{"wen","zong"});

 

//

 

//普通属性方法

//获得

Field i=clazz.getDeclaredField("i");//对私有的处理

Method add=clazz.getMethod("add", new Class[]{Integer.class,Integer.class});

 

//生成对象

//Object o=clazz.newInstance();无参数时

Constructor cst=clazz.getConstructor(new Class[]{String.class,Double.class});

Object o =cst.newInstance(new Object[]{"s1",new Double(10)});

 

 

//使用

i.setAccessible(true);//对私有的处理

i.get(o);

i.set(o, 2);

add.invoke(o, new Object[]{new Integer(1),new Integer(1)});

 

/

 

//验证

System.out.println(static_s.get(null));//aa

System.out.println(static_addString.invoke(null, new Object[]{"wen","zong"}));//wen_zong

System.out.println(i.get(o));//2

System.out.println(add.invoke(o, new Object[]{new Integer(1),new Integer(1)}));//2

}

 

}

我的话费充值店-各种面额
电信100元仅售98.60 

联通100仅售99.00
移动100仅售99.30

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值