关于理解JDK的反射机制,Reflect

package com.hk.ztry;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class TestReflect 
{
    private Class<?> classType;
    
    public TestReflect(String name) throws Exception
    {
        this.classType = Class.forName(name);
    }
    
    public TestReflect()
    {
        
    }
    
    //(1)获取方法
    public void getMethod()
    {
        Method[] methods = this.classType.getDeclaredMethods();
         
         for(Method method : methods)
         {
            System.out.println(method);
            }
    }
    //(2)通过反射调用方法
    public void invokeMethod() throws Exception
    {
        Class<?> my_classType = TestReflect.class;
         
        //注意,这里一定要有空的构造函数,否则报错
        Object TestReflect_object = my_classType.newInstance();
         
        Method add_Method = my_classType.getMethod("add", new Class[] { int.class,int.class });
         
        Object result = add_Method.invoke(TestReflect_object, new Object[] { 1, 2 });
         
        System.out.println(result);
    }
    
    //(3)生成对象
    public void constructObject() throws Exception
    {
        Class<?> my_classType = TestReflect.class;
         Constructor cons_string = my_classType.getConstructor(new Class[] {String.class});
         //调试发现,这个确实是Double类型,但是,如何使用呢
         Object obj_Typedouble = cons_string.newInstance(new Object[] {"java.lang.Double"});
    }
    
     public int add(int param1, int param2)
     {
         return param1 + param2;
     }
    
     public static void main(String[] args) throws Exception
     {
         TestReflect t1=new TestReflect("java.lang.String");
         
         t1.getMethod(); 
         
         t1.invokeMethod();
         
         t1.constructObject();
     }
}
http://www.cnblogs.com/mengdd/archive/2013/01/26/2877972.html

参考文献的地址·

 

posted @ 2015-08-12 14:40  爱吃萝卜干  阅读(285)  评论(0编辑  收藏  举报