I've researched this issue a great deal, but have not been very successful in finding a solution close to my situation. I apologize if I am redundant.
Anyway, I am new to generics and so I'm not entirely clear on the syntax. But here is my situation:
I have an Interface (let's call it IService) and an implementation (ServiceImpl). The implementation class has an abstract method that is to be overridden by an extending class (ServiceExt).
I have an abstract bean (let's call it AbstractBean) which has a few fields and is meant to be extended by another bean (BeanExt) in order to add some more fields.
Ok, now that the situation is laid out, here is my abbreviated code:
Interface:
public interface IService <B extends AbstractBean> {
B method(B bean, Object data) throws Exception;
}
Implementation:
public abstract class ServiceImpl <B extends AbstractBean> implements IService<B> {
public abstract B method(B bean, Object data);
}
Abstract Bean:
public abstract class AbstractBean{
private String fname;
private String lname;
[getters and setters]
}
Extended Bean:
public class BeanExt extends AbstractBean{
private String phoneNum;
[getter and setter]
}
Extending Class: aka Class giving me issues
public class ServiceExt <B extends AbstractBean> extends ServiceImpl <B> {
#Override
public <B> BeanExt method(Bbean, Object data) {
if(beaninstanceof AbstractBean){
BeanExt beanExt = (BeanExt) session;
beanExt.setFname("John");
beanExt.setLname("Doe");
beanExt.setPhoneNum("123456789");
return beanExt;
}else{
return null;
}
}
}
Ok, so now eclipse is giving me all kinds of non-descriptive issues and I don't know what to do. I've played around with the extending class methods a ton but have not found success. Above is how it looks after my last tinkering.
The issues currently presented by my IDE within the class ServiceExt are:
The method method(B, Object) of type ServiceImpl must override or implement a supertype method
The type ServiceExt must implement the inherited abstract method [some other non-abstract method in the interface]
Edit: For further clarification, what I am ultimately trying to do is:
Create a bean which extends the AbstractBean and add another field
Define the abstract method inside the class ServiceExt
Within the method, set some values in the extended bean
Return the extended bean with its new values
Update - I've taken all of your input and the changes are reflected below. The issue currently presented by my IDE within the class ServiceExt is:
The type ServiceExt must implement the inherited abstract method [some other non-abstract method in the interface]
Interface:
public interface IService <B extends AbstractBean> {
B method(B bean, Object data) throws Exception;
B otherMethod(HttpServletRequest request) throws Exception;
}
Implementation:
public abstract class ServiceImpl <B extends AbstractBean> implements IService<B> {
public abstract B method(B bean, Object data);
#Override
public final B otherMethod(HttpServletRequest request) {
return [something];
}
}
Abstract Bean:
public abstract class AbstractBean{
private String fname;
private String lname;
[getters and setters]
}
Extended Bean:
public class BeanExt extends AbstractBean{
private String phoneNum;
[getter and setter]
}
Extending Class: aka Class giving me issues
public class ServiceExt extends ServiceImpl <BeanExt> {
#Override
public BeanExt method(BeanExt bean, Object data) {
BeanExt beanExt = (BeanExt) session;
beanExt.setFname("John");
beanExt.setLname("Doe");
beanExt.setPhoneNum("123456789");
return beanExt;
}
}
You are not really overriding the method in super class. Here's the overridden method:
#Override
public BeanExt method(BeanExt bean, Object data) {
BeanExt beanExt = (BeanExt) session;
beanExt.setFname("John");
beanExt.setLname("Doe");
beanExt.setPhoneNum("123456789");
return beanExt;
}
Since you're extending from ServiceImpl<BeanExt>, the type parameter B is replaced with BeanExt type, so does the return type and parameter of the method.
Also note that I've removed the instanceof check, as it is really not needed. bean will always be an instance of AbstractBean, because that is enforced by the bound you gave to the type parameter declaration of ServiceImpl class.
I did not entirely understand what you're trying to do, but is this acceptable/working?
public class ServiceExt <B extends BeanExt> extends ServiceImpl <B> {
#Override
public B method(B bean, Object data) {
bean.setFname("John");
bean.setLname("Doe");
bean.setPhoneNum("123456789");
return bean;
}
}
I just corrected all the errors:
interface IService <B extends AbstractBean> {
B method(B bean, Object data) throws Exception;
}
abstract class ServiceImpl <B extends AbstractBean> implements IService<B> {
public abstract B method(B bean, Object data);
}
abstract class AbstractBean{
String fname;
String lname;
}
class BeanExt extends AbstractBean {
String phoneNum;
}
class ServiceExt <B extends AbstractBean> extends ServiceImpl <B> {
#Override public B method(B bean, Object data) {
if (bean instanceof BeanExt) {
BeanExt beanExt = (BeanExt) bean;
beanExt.fname = "John";
beanExt.lname = "Doe";
beanExt.phoneNum = "123456789";
return bean;
}else{
return null;
}
}
}
Related
I have this Interface:
public interface Test<T> {
default Class<?> getT() {
return T.getClass(); < --error
}
}
next i have a class that implements it:
static class ItemService implements Test<Item>{
}
And i want to get the 'Item' class from the 'ItemService' class
static ItemService service = new ItemService();
private static void k() {
System.out.println(service.getT());
}
Now one way to do it is this:
public interface Test<T> {
default Class<?> getT() {
return Type.type;
}
class Type {
public static Class<?> type;
}
}
Service:
static class ItemService implements Test<Item> {
public ItemService() {
Type.type = Item.class;
}
}
And it works fine but there is a problem,
When another class implement the interface:
static class OrderService implements Test<Order> {
public OrderService() {
Type.type = Order.class;
}
}
And i try:
static ItemService service = new ItemService();
static OrderService orderservice = new OrderService();
private static void k() {
System.out.println(service.getT());
}
I get the Order class and not the Item class
How can i make it work?
Classes inside interfaces are static, You can remove the default from the function and every class will need to implement this. example:
public interface Test<T> {
public Class<T> getT();
}
static class ItemService implements Test<Item> {
public Class<Item> getT() {return Item.class;}
}
static class OrderService implements Test<Order>{
public Class<Order> getT() {return Order.class;}
}
An alternative could be an abstract class.
public interface Test<T> {
public Class<T> getT();
}
abstract class AbstractTest<T> implements Test<T> {
private final Class<T> type;
AbstractItemService(Class<T> type) { this.type = type }
public Class<T> getT() {return type;}
}
class ItemService extends AbstractTest<Item> {
ItemService() { super(Item.class); }
// implement other things
}
class OrderService extends AbstractTest<Order>{
OrderService() { super(Order.class); }
// implement other things
}
Here is another option, if your implementation has an instance of T.
interface Test<T>{
T getT();
default Class<?> getClassOfT(){
return getT().getClass();
}
}
I'm writing Java program, which interacts with Db via Hibernate.
All my persistent classes extend from common abstract class Entity which implements interface IEntity. For example:
public interface IEntity {
long getId();
void setId(long id);
}
public abstract class Entity implements IEntity {
private long id;
//get + set id
}
public class User extends Entity {
private string name;
//get + set name
}
public class Item extends Entity {
private string description;
//get + set description
}
For operations with Db I created repository classes which extend from Repository<T extends IEntity> with standard CRUD methods for all entities and this class implements interface IRepository<T extends IEntity>:
public interface IRepository<T extends IEntity> {
void create(T object) throws JDBCException;
//other CRUD operations
}
public abstract class Repository<T extends IEntity> implements IRepository<T> {
private final Class<T> entityClass;
protected final EntityManager entityManager;
public Repository(Class<T> entityClass, EntityManager entityManager) {
this.entityClass = entityClass;
this.entityManager = entityManager;
}
#Override
public void create(T object) throws JDBCException {
entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();
}
//other CRUD operations implementation
}
public class UserRepository extends Repository<User> {
public UserRepository (EntityManager entityManager) {
super(AmountUnit.class, entityManager);
}
}
public class ItemRepository extends Repository<Item> {
public ItemRepository (EntityManager entityManager) {
super(AmountUnit.class, entityManager);
}
}
This structure worked well until I decided to create method to obtain specific repository by its entity class.
I see this method as something like this:
public <T extends IEntity, U extends IRepository<T>> U getByType(T object) {
// code here
}
Let's say, that class User extends Entity and have repository class UserRepository extends Repository<User>
I'm expecting, that this method should return RepositoryforUser object`.
From my point of view this can be achieved in two ways:
Elegant. Create method for IRepository - Class<T> getEntityClass
and then compare classes of input and result of getEntityClass
Stupid. Make many if/else statements inside this method and return repository. if(object instanceof A) return ARepository
public class Storage {
private IRepository<? extends IEntity>[] repositories;
public <T extends IEntity, U extends IRepository<T>> U getByTypeVar1(T object) {
for (IRepository<?> repo : repositories) {
if (object instanceof repo.getEntityClass ()) // cannot resolve getEntityClass
return repo;
}
}
public <T extends IEntity, U extends IRepository<T>> U getByTypeVar2(T object) {
if (object instanceof UserRepository.getEntityClass ())
return UserRepository; //incompatible type
//more if else here
}
}
But both of these implementation are failed to compile. May be you have any ideas how to write this method correctly
You can implement the getByType method like this (I changed the parameter type):
private List<IRepository<? extends IEntity>> repositories;
#SuppressWarnings("unchecked")
public <E extends IEntity> IRepository<E> getByType(Class<E> entityClass) {
for (IRepository<?> repository : repositories) {
if (repository.getEntityClass().equals(entityClass)) {
return (IRepository<E>) repository;
}
}
throw new IllegalArgumentException(
"No repository for entity class " + entityClass.getName());
}
When you post your code that failed to compile, we can figure out where the problem was.
Update (code comments)
You should add the getEntityClass() method to IRepository.
To make the code less complicated, you can replace:
<T extends IEntity, U extends IRepository<T>> U getByType()
with
<T extends IEntity> IRepository<T> getByType getByType()
Using instanceof in
object instanceof repo.getEntityClass ()
can be problematic, since you can have entity hierarchies and you can get a wrong (subclass) repository for an object. If you don't know a class of the object, you can get it by (the object can be a Hibernate proxy):
org.hibernate.Hibernate.unproxy(object).getClass()
and then compare the classes by repository.getEntityClass().equals(entityClass).
let imagine I have per entity a repository class (spring data jpa) for database access and a service class. The dependencies are managed by spring framework. Every service method does in most cases the same, so there is mainly code duplication:
public class NewsService {
#Inject
private NewsRepository newsRepository;
public void add(News news) {
// do some validation
newsRepository.save(news);
}
}
public class UserService {
#Inject
private UserRepository userRepository;
public void add(User user) {
// do some validation
userRepository.save(user);
}
}
Now i thought about creating an abstract class like this:
public abstract class AbstractService<T> {
private UnknownRepository unknownRepository;
public void add(T entity) {
// do some validation
unknownRepository.save(entity);
}
}
public class NewsService extends AbstractService<News> {
}
public class UserService extends AbstractService<User> {
}
My problem: How can i overwrite the repository used inside the abstract class based on my entities?
You can replace the UnknownRepository field with an abstract method and a type parameter:
// R is the type of the repository
public abstract class AbstractService<T,R extends BaseRepository> {
protected abstract R getRepository();
public void add(T entity) {
getRepository().save(entity);
}
}
And inject the specific repository to the implementations of this class:
public class NewsService extends AbstractService<News, NewsRepository> {
#Inject private NewsRepository newsRepository;
#Override
public NewsRepository getRepository() {
return newsRepository;
}
// the inherited add() method works now
}
currently I'm trying to implement a typed generic DAO.
I do not even get to compile anything, since NetBeans complains about UserDAOHibernate
interface expected here
type argument User is not within bounds of type-variable ENTITY
I'm afraid there is some obvious mistake in how I use inheritance/interfaces, since I'm rather new to Java.
Here's some stripped down code
public interface GenericEntity<ID extends Serializable> {
public abstract ID getId();
public abstract void setId(final ID id);
}
public abstract class LongEntity implements GenericEntity<Long> {
protected Long id;
public Long getId();
public void setId(final Long id);
}
public class User extends LongEntity implements Serializable {
private String name;
private String password;
private Customer customer;
}
public interface GenericDAO<ENTITY extends GenericEntity<ID>, ID extends Serializable> {
public abstract ENTITY findById(ID id);
public abstract List<ENTITY> findAll();
public abstract ENTITY makePersistent(ENTITY entity);
public abstract void makeTransient(ENTITY entity);
}
public abstract class GenericHibernateDAO<ENTITY extends GenericEntity<ID>, ID extends Serializable>
implements GenericDAO<ENTITY, ID> {
}
public class UserDAOHibernate implements GenericHibernateDAO<User, LongEntity> {
}
Is it that LongEntity should extend GenericEntity<Long>? If so, how would I do this with Java's single level or inheritance?
Is this layered approach a bad example to follow? All my entities need an id and this implementation could easily be reused lateron with different id types, so I thought I might use it.
The error comes from here:
public class UserDAOHibernate implements GenericHibernateDAO<User, LongEntity> {
}
You've specified that GenericHibernateDAO's ID parameterized type is bounded by <ID extends Serializable>.
LongEntity extends GenericEntity, and hence, why you have a type mismatch.
Also, GenericHibernateDAO is an abstract class (and not an interface), so you'll need to extends instead of implements.
The correct solution should be:
public class UserDAOHibernate extends GenericHibernateDAO<User, Long> {
}
I have a controller superclass and its subclass:
public class SuperController {
#Resource
private A resourceA;
}
public class SubController extends SuperController {
#Resource
private B resourceB;
}
I don't use resourceA field in Subcontroller, but Subcontroller acts as SuperController and has the same methods. So how can I forbit the inheritance of #Resource annotation, just like that:
public class SuperController {
**private** #Resource
private A resourceA;
}
Sounds like you need a common abstract class if the sub-class doesn't use some of the fields of the parent class.
public abstract class AbstractController {
// common fields.
// common methods.
}
public class SuperController extends AbstractController {
#Resource
private A resourceA;
}
public class SubController extends AbstractController {
#Resource
private B resourceB;
}