0

以下のキャストを回避できる方法はありますか?

//Is there a way this can be implemented so the cast is not necessary? 
FooService fooService = new FooService();
Foo f = (Foo)fooService.findById(id);

public class FooService extends DomainServiceImpl<Foo> {
}

public class DomainService<T extends Persistable>{

   private Class<T> type;

   public void findById(long id) {
      domainDao.findById(id, type);
   }
}

編集:まだキャストする必要があります

public T findById(long id) {
    return (T) fooDao.findById(id, type);
}
4

2 に答える 2

1

うーん、これがコメントのツリーを取得する前に、ニーズに合ったソリューションを投稿します。ただし、特定の問題に合わせて調整する必要があります。

主なアイデアは、メソッドfindByIdがジェネリック型を返すTため、コードで型キャストを必要としないということです。

class Solution {
  static class Foo extends Persistable {
  }

  public static void main(String[] args) {
    FooService fooService = new FooService();
    Foo f = fooService.findById(0l);
  }

  static class FooService extends DomainService<Foo> {
    FooService() {
      type = Foo.class;
    }
  }

  static class Persistable {
  }

  static class DomainService<T extends Persistable> {

    Class<T> type;

    public T findById(long id) {
      try {
        return this.type.newInstance();
      }
      catch (InstantiationException e) {
        throw new RuntimeException(e);
      }
      catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    }
  }
}
于 2013-11-05T08:31:18.803 に答える
0

以下を使用できます。

type.cast(object);

警告を回避します。

これでも ClassCastException がスローされる可能性があることに注意してください。

オブジェクトをキャストできるかどうかわからない場合は、次を確認してください。

if (type.isInstance(object)){
    return type.cast(object);
} else {
   ... 
}
于 2013-11-05T08:58:04.063 に答える