开发者

Java : Is there a way to automatically cast a return value?

I have two classes :

public abstract class Arguments {
    public List execute() {
        // do some stuff and return a list
   开发者_Python百科 }
}

// and a child :
public class ItemArguments {
    public List<Item> execute() {
        return super.execute();
    }
}

As you can see, the method execute in ItemArguments is a bit useless, but without it, I have to cast all my calls to the execute method in Arguments.

Is there a way to remove the execute method in ItemArguments and avoid having the cast to do where the calls are made ?

Thanks for your help!


Generics

public abstract class Arguments<T> {
  public List<T> execute() {
    // some stuff
    return new ArrayList<T>();
  }
}

public class ItemArguments extends Arguments<Item> {

}

You don't even need to subclass unless you have other reasons to do so

public class Arguments<T> {
  public List<T> execute() {
    // blah
  }
}

Arguments<Item> o1 = new Arguments<Item>();
List<Item> o2 = o1.execute();

Calling methods on T is not quite so straightforward. T is erased by the compiler and so it's not available at runtime. An easy to understand workaround is to pass in the class when you instantiate Arguments

public class Foo {
  public static void something() { ... }
}

public class Arguments<T extends Foo> {
  private Class<? extends Foo> foo;
  public Arguments(Class<? extends Foo> foo) {
    this.foo = foo;
  }
  public List<T> execute() {
    foo.something();

  }
}

There are better ways, but this is mostly understandable without being a patterns master :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜