返回一个对象而不必事后再投射

时间:2014-12-13 19:37:59

标签: java

我有一个方法可以使用不同的类来实现相同的公共接口。接口是通用的,实现它的类可以包含任何类型的对象作为实例变量。我的方法使用的所有类都包含不同类型的对象。我需要我的方法来返回给定类包含的对象。由于包含的对象可以是任何类型,因此我强制将返回值强制转换为" Object"然后在我使用该值时将其向下转发。有没有更好的解决方法呢?

public class Foo {

    // this method is the problem since it can't keep the type getData returns
    public static Object method(I i) {
        return i.getData();
    }

    public static void main(String[] args) {
        I a = new A();
        I b = new B();
        Integer s1 = (Integer)method(a);  // this should work without the cast
        Integer s2 = method(b);  // this shouldn't work of course
    }


    public static interface I<T> {

        public T getData();

    }

    public static class A implements I<Integer> {

        public Integer getData() {
            return 1;
        }

    }

    public static class B implements I<String> {

        public String getData() {
            return "data";
        }

    }

}

1 个答案:

答案 0 :(得分:1)

public static  <T> T method(I<T> i) {
    return i.getData();
}
相关问题