java设计模式--反射技术

java反射技术应用广泛,Spring IoC的基本原理也应用到了反射技术,它能够通过配置:类的全限定名、方法和参数,完成对象的初始化,甚至反射某些方法,大大增强了java的可配置性。

一,首先写一个需要被反射的类。

package reflect;

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


public class ReflectServiceImpl {
    public void sayHello(String name) {
        System.err.println("Hello " + name);
    }

}

二,然后写测试代码,反射出以上类的对象或者方法。

package reflect;

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

public class ReflectTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
         ReflectTest ts = new ReflectTest();
         Object obj =  ts.reflectMethod();
     
    }
     
    //反射出对象
    @SuppressWarnings("deprecation")
    public ReflectServiceImpl getInstance() {
        ReflectServiceImpl object = null;
        try {
            //此处生成一个对象,给类加载器传入类的全限定名,通过newInstance方法初始化一个类对象
            object = (ReflectServiceImpl) Class.forName("com.lean.ssm.chapter2.reflect.ReflectServiceImpl")
                    .newInstance();
            
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            ex.printStackTrace();
        }
        return object;
    }

    //反射出方法
    public Object reflectMethod() {
        Object returnObj = null;
        ReflectServiceImpl target = new ReflectServiceImpl();
        try {
            //反射出方法
            Method method = ReflectServiceImpl.class.getMethod("sayHello", String.class);
            //方法调用
            returnObj = method.invoke(target, "mit zhang");
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException ex) {
            ex.printStackTrace();
        }
        return returnObj;
    }

    

}

三,参考资料

《java EE 互联网框架整合开发》 杨开振  著

 

posted @ 2020-08-22 17:48  dabao2021  阅读(83)  评论(0编辑  收藏  举报