【问题标题】:Figure the parameter to pass of the invocation of a method via reflection图通过反射调用方法的参数
【发布时间】:2016-04-25 11:49:16
【问题描述】:

我有一组实现通用接口的类,例如:

public inteface CustomGenerator {  
   Object generate(Reader r);  
} 

这些类可以相应地处理参数并生成预期类型的​​响应。
我有一个需要填充的基类。为了填充类,我使用这些自定义生成器类和反射。

public static void copy(CustomClass target, String tag, Reader reader) {  
   Object input = CustomGenerators.get(tag).generate(reader); 
   String setter = setterNames.get(tag);   
   Method m = target.getClass().getMethod(setter, input.getClass());  
   m.invoke(target, input);   
}  

}

为清楚起见省略了异常处理。 这可行,但我想要以下地址:
问题:
传入的一些 types 没有自定义生成器来解析它们,因为它们本质上是基元,并且 1) 我不想创建许多小类只是为了做一些琐碎的事情,比如 Integer.valueOf(reader.nextString());
另一方面,当我调用target.getClass().getMethod 时,我需要参数类型,并且需要处理原始值的情况。
所以我需要以某种方式在这里弄清楚:
target.getClass().getMethod(setter, input.getClass()); 我需要传递的第二个参数是什么。

我怎样才能彻底解决这个问题?

【问题讨论】:

  • 您使用String type 而不是Class<?> clazz 有什么原因吗?原语确实有相应的类对象。你可以像往常一样得到它们:int.class,就像你会做String.class
  • @DzmitryPaulenka:type 不是一个类。这是一个“标签”字符串,我可以理解如何处理
  • 例如 int 情况下的“标签”是什么?
  • 它只是来自具有标签和值的文件的流。这都是预定义的,我知道那个标签,例如“利润”是要被解析为整数的东西(我的意思是关联的值;读者会注意这一点)

标签: java oop design-patterns reflection parameters


【解决方案1】:

这样的事情怎么样?

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class Main {
    static final Map<String, CustomGenerator> generators = new HashMap<String, CustomGenerator>();
    static final Map<String, String> setterNames = new HashMap<String, String>();
    static final Map<Class<?>, Class<?>> wrappers = new HashMap<Class<?>, Class<?>>();

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        wrappers.put(int.class, Integer.class);
        wrappers.put(double.class, Double.class);
        wrappers.put(boolean.class, Boolean.class);
        //...

        generators.put("int", new PrimitiveCustomGenerator(int.class));
        generators.put("double", new PrimitiveCustomGenerator(double.class));
        generators.put("boolean", new PrimitiveCustomGenerator(boolean.class));
        //...

        setterNames.put("int", "setInt");
        //...

        CustomClass holder = new CustomClass();
        System.out.println(holder.intValue);

        copy(holder, "int", new Reader());
        System.out.println(holder.intValue);
    }

    static void assertThat(boolean condition) {
        if (!condition) {
            throw new IllegalStateException();
        }
    }

    public static class CustomClass {
        private int intValue;

        public void setInt(int intValue) {
            this.intValue = intValue;
        }
    }

    public static void copy(CustomClass target, String tag, Reader reader) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        CustomGenerator generator = generators.get(tag);
        Object input = generator.generate(reader);

        String setter = setterNames.get(tag);
        Method m = target.getClass().getMethod(setter, generator.getTargetClass());
        m.invoke(target, input);
    }

    public static class Reader {
        public String nextString() {
            return "22";
        }
    }

    public interface CustomGenerator {
        Class getTargetClass();
        Object generate(Reader r) throws InvocationTargetException, IllegalAccessException;
    }

    public abstract static class AbstractCustomGenerator implements CustomGenerator {
        protected Class<?> targetClass;

        AbstractCustomGenerator(Class<?> targetClass) {
            this.targetClass = targetClass;
        }

        public Class<?> getTargetClass() {
            return targetClass;
        }
    }

    public static class PrimitiveCustomGenerator extends AbstractCustomGenerator {

        private final Method valueOfMethod;
        private final Class<?> wrapperClass;

        PrimitiveCustomGenerator(Class<?> targetClass) throws NoSuchMethodException {
            super(targetClass);
            assertThat(targetClass.isPrimitive());

            // use google-guava lib
            // Class wrapperClass = com/google/common/primitives/Primitives.wrap(targetClass);
            wrapperClass = wrappers.get(targetClass);

            valueOfMethod = wrapperClass.getMethod("valueOf", String.class);
            assertThat(Modifier.isStatic(valueOfMethod.getModifiers()));
        }

        public Object generate(Reader r) throws InvocationTargetException, IllegalAccessException {
            return valueOfMethod.invoke(wrapperClass, r.nextString());
        }
    }
}

【讨论】:

  • 抛开你传递“int”等的事实,而在我的情况下,标签不是实际类型,而是读者可以解析值的一些描述性字符串,你的代码与我所拥有的相似或多或少。 setter 的 hashmap 和要为 setter 映射的另一个 hashmap 命名参数类型。如果可能的话,如果有另一种方法/方法来避免映射到参数类型,我很感兴趣
  • 好吧,我想我现在明白了 :) 好吧,你不能从 Object 中确定原始类型,因为那时它已经被装箱了。所以obj.getClass() 将返回java.lang.Integer 等。
  • 另一种方法是使用 Method 实例的映射,而不仅仅是 setterNames
  • 您发布的代码结构是否遵循设计模式?
  • 我不知道...也许是策略?为什么?
猜你喜欢
  • 2016-05-26
  • 2011-01-26
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
  • 2020-12-09
相关资源
最近更新 更多