【问题标题】:Execute a specific parametrized class method执行特定的参数化类方法
【发布时间】:2013-09-25 22:47:32
【问题描述】:

我有这个(简化的)java 接口

public interface MyInterface<T> {
    public String run( T arg );
}

以及一些实现该接口的类,即

public final class SomeImplementation1 implements MyInterface<String> {
   @Override
   public String run( String arg) {
       // do something with arg and return a string
   }
}

public final class SomeImplementation2 implements MyInterface<CustomClass> {
   @Override
   public String run( CustomClass arg) {
       // do something with arg and return a string
   }
}

现在,我有一个用于所有这些实现的全局资源管理器,它将所有这些实现实例化到一个列表中以供以后使用。我想要实现的是这样的,这显然给了我一个错误

public final class MyInterfaceManager {
    private List<MyInterface<?>> elements = new List<MyInterface<?>>();

    public MyInterfaceManager() {
        elements.put( new SomeImplementation1() );
        elements.put( new SomeImplementation2() );
        // more implementations added
    }

    // this is what I would like to achieve
    public <T> void run( T arg ) {
        for( MyInterface<?> element: elements ) {
            String res = element.run( arg );    // ERROR
        }
    }
}

因为“arg 无法通过方法调用转换转换为 ? 的 capture#1”。 一个可能的解决方案是在循环内执行instanceof 测试,并将元素与参数一起转换为其真实类型,就像这样

    public <T> void run( T arg ) {
        for( MyInterface<T> element: elements ) {
            if (element instanceof SomeImplementation2) {
                String res = ((SomeImplementation2)element).run( (CustomClass)arg  );
            } else if // other tests here ...
        }
    }

但我不喜欢它,它一点也不优雅,它迫使我做很多instanceof 和演员表。 所以,我想知道是否有更好的方法来实现这一点。 谢谢你的帮助:)

【问题讨论】:

  • 您将getClass 类型方法添加到interface 中,然后简单地检查assignableFromList 中的每个实例以查看传入的参数是否可以安全地转换为所需的参数,然后你 Class.cast 进行转换。
  • @BoristheSpider 谢谢你的建议,我明天试试,因为这里有点晚了:)
  • @BoristheSpider 你应该这样回答。

标签: java generics methods


【解决方案1】:

您遇到了type erasure。您需要向interface 添加另一个方法,该方法返回与类型参数&lt;T&gt; 相关的Class 实例,这将允许您对该Class 进行运行时检查。

我会这样做:

public interface MyInterface<T> {
    String run( T arg );
    Class<T> type();
}

所以interface 返回它的类型。注:所有interface 成员默认为public - 不需要额外的public

public final class SomeImplementation1 implements MyInterface<String> {
   @Override
   public String run(final String arg) {
       return arg;
   }

   @Override
   public Class<String> type() {
       return String.class;
   } 
}

@SuppressWarnings({"unchecked"})
public static  <T> String run(final T arg) {
    for (final MyInterface<?> element : elements) {
        if (element.type().isAssignableFrom(arg.getClass())) {
            return ((MyInterface<T>) element).run(arg);
        }
    }
    throw new IllegalArgumentException("No element found.");
}

逻辑是,对于每个MyInterface,您检查提供的参数是否可以安全地转换为MyInterfacetype()。如果是,那么您可以将整个 MyInterface 转换为 arg 的类型。这是未选中的,因为编译器无法将其验证为编译时间,但是当您手动进行检查时,可以忽略此警告。

public static void main(String[] args) throws Exception {
    elements = new LinkedList<>();
    elements.add(new SomeImplementation1());

    System.out.println(run("test"));
    System.out.println(run(1));
}

输出:

test
Exception in thread "main" java.lang.IllegalArgumentException: No element found.
    at com.XXX.App.run(App.java:33)
    at com.XXX.App.main(App.java:55)

正如预期的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多