JAVA 反射之方法调用

来源:互联网 发布:ps淘宝主图广告 编辑:程序博客网 时间:2024/05/01 16:21

刚才看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[])
    
// {
    
// }

}

 

 

原创粉丝点击