简体   繁体   中英

Avoid cast in java (Generics)

Is the a way the cast below can be avoided?

//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);
   }
}

edit: Still have to cast

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

Hmm, before this gets a tree of comments I will post a solution which might fit your needs. You'll have to adapt it to your specific problem however.

The main idea is, that the method findById is returning the generic type T so you do not need the type cast in your code.

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);
      }
    }
  }
}

You can use:

type.cast(object);

to avoid the warning.

Note that this still might throw a ClassCastException.

If you're not sure that the object can be cast, check with:

if (type.isInstance(object)){
    return type.cast(object);
} else {
   ... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM