java 6/7/8中是否有可用于java反射的备用功能?

时间:2017-02-28 10:55:20

标签: java

要动态调用方法,java 6/7/8中除了java反射之外还有其他任何可用的功能吗?

另外,java 7/8中的java反射是否有任何改进?

下面是我使用反射的当前代码,但我需要在没有反射的情况下实现我的业务逻辑。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Core {

    public static void main(String[] arg) {
        Core core = new Core();
        Map<Object, Object> obj = new HashMap<Object, Object>();
        core.create(obj);
    }

    public Map create(Map<Object, Object> obj) {

        // TODO implement core business logic
        System.out.println("Core Business Logic Completed");
        try {
            obj = invokeAfter(obj);
        } catch (SecurityException | IllegalArgumentException | ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }

    public Map invokeAfter(Map<Object, Object> obj) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException,
            IllegalArgumentException, InvocationTargetException {

        Class params[] = {};
        // TODO below list will be injected using spring configuration in
        // configurable approach
        List<String> afterClassNameList = new ArrayList<String>();
        afterClassNameList.add("Custom11");
        afterClassNameList.add("Custom22");

        if (!afterClassNameList.isEmpty()) {
            for (String className : afterClassNameList) {
                System.out.println("Class Name::" + className);
                Class thisClass = Class.forName(className);
                Object iClass = thisClass.newInstance();
                Method thisMethod = thisClass.getDeclaredMethod("create", params);
                obj = (Map<Object, Object>) thisMethod.invoke(iClass, obj);
            }
        }
        return obj;
    }
}



  public class Custom1 {
    public Map create(Map<Object, Object> obj) {
        // TODO implement custom business logic
        return obj;
    }
}



   public class Custom2 {
    public Map create(Map<Object, Object> obj) {
        // TODO implement custom business logic
        return obj;
    }
}

1 个答案:

答案 0 :(得分:3)

更好的选择是使用您的实现实现的接口。

interface Builder<T> {
   T create(Map<?, ?> properties;
}

class Custom1 implements Builder<Map> {

您可以使用字节代码生成,检测或运行时编译,但这些比使用反射更复杂。

如果您使用的是Java 8,则可以使用Function<Map, Map>作为现有界面。