反射机制

来源:互联网 发布:王自健 郭德纲 知乎 编辑:程序博客网 时间:2024/06/05 15:19

文章来源: http://czh.iteye.com/blog/604262


package com;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Test{
    private String str = "123";
    static{
        System.out.println("Test Load");
    }
    
    public void test(){
        System.out.println("test method");
    }
    
    public static void test1(String name){
        System.out.println("test1 method");
    }
}
public class Reflect_class {
    public static void main(String args[]){
        System.out.println(Test.class);
        
        try{    
            Test test = new Test();
            //加载TEST
            Class testClass = Class.forName("com.Test");
                Object object = testClass.newInstance();
            
            //获取Method
            Method[] testMethod = testClass.getDeclaredMethods();
            System.out.println(testMethod[0].getName());
            testMethod.getClass();
            
            
            //获取fields的相关信息
            Field fields[] = testClass.getDeclaredFields();
            for(Field field : fields){
                System.out.println(field.getName());
                System.out.println(field.getType());
                System.out.println("field type is class ?" + field.getType().isInstance(new String()));
            }         
            try {
                //调用方法
                Method method = testClass.getDeclaredMethod("test", new Class[]{});
                method.invoke(test, new Object[]{});
                Method method2 = testClass.getDeclaredMethod("test1", new Class[]{String.class});
                method2.invoke(test, new Object[]{new String("new String")});
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch(ClassNotFoundException e){
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
原创粉丝点击