java 反射机制 reflect

 1.获取某个对象的Class,也就是.class,一般是通过如下两种方式可以获得。
     第一种方式:Class.forName("T"); T代表对象的名称(包括该对象的包名),如:Class.forName  ("org.wsay.ttitfly.ReflectMethod");
    第二种方式:T.class 即可,T代表该对象名称(不包括该对象的包名),如:ReflectMethod.class
   还有一种独特的方式是专门针对int,long ..的包装对象Integer,Long...的,如Integer.Type  表示基
   本类型 int 的 Class 实例
2, Method.invoke(Object o,Object...args),调用对象o的Method封装的方法,参数为args,args可以是个参数列表,也可以是个参数数组. 详细见下面例子.
package org.wsay.ttitfly;
import java.lang.reflect.Method;
public class ReflectMethod {
 
 public static void main(String[] args)
 {
      try
      {
            Class rm = Class.forName("org.wsay.ttitfly.ReflectMethod"); //第一种方式获取该对象的Class
            //Class rm = ReflectMethod.class;//第二种方式获得
           //表示调用ReflectMethod的add方法,有2个int参数
           Method method = rm.getMethod("add", Integer.TYPE,Integer.TYPE);
           //   Object []o = new Object[2];
           //   o[0] = new Integer(2);
           //   o[1] = new Integer(3);
           Integer result = (Integer) method.invoke(new ReflectMethod(),2,3);//参数列表
          // Integer result = (Integer) method.invoke(new ReflectMethod(),o);//参数数组
          System.out.println(result.intValue());
       }
      catch (Exception e)
      {
            e.printStackTrace();
      }
 }
 public int add(int a,int b)
 {
        return a+b;
 }
}
打印结果为:5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值