JAVA 反射之方法调用

刚才看Tomcat6源码时,发现一段有趣的使用JAVA反射机制的代码。考出来处理,独立运行,成功。贴与大家分享。

 

package angel.lang.reflect.ut;

import java.lang.reflect.Method;

import junit.framework.TestCase;

/**
 * 
 * <pre>
 *  Description:    
 *  TODO Unit测试类
 * 
 *  Revision History:
 *  Feb 1, 2008 Fity.Wang        initial version.
 * 
 * </pre>
 
*/

public class MethodUT extends TestCase
{
    
public void testInvoke()
    
{
        
try
        
{
            Class commonfor 
= Class.forName("angel.lang.reflect.ut.CommonFor");
            Object cfinstance 
= (Object) commonfor.newInstance();
            Class paramTypes[] 
= new Class[1];
            paramTypes[
0= Class.forName("java.lang.String");
            Object paramValues[] 
= new Object[1];
            paramValues[
0= new String("Hello Method invoke!");
            Method method 
= cfinstance.getClass().getMethod("methodForInvoke",
                    paramTypes);
            method.invoke(cfinstance, paramValues);
        }

        
catch (Exception e)
        
{
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

 

package angel.lang.reflect.ut;

import static java.lang.System.out;

/**
 * 
 * <pre>
 *  Description:    
 * TODO 反射测试目标类
 * 
 *  Revision History:
 *  Feb 1, 2008 Fity.Wang        initial version.
 * 
 * </pre>
 
*/

public class CommonFor
{
    
public static String getClassName()
    
{
        
return "[" + CommonFor.class.getName() + "]";
    }


    
public void methodForInvoke(String s)
    
{
        out.println(getClassName() 
+ "methodForInvoke()" + s);
    }

    
// public static void main(String args[])
    
// {
    
// }

}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值