Implement a generic interface - java

I have a generic interface and I would like to implement this interface in a generic way :
public interface BaseBean<T> {
public T create(T t);
public T read(Long id);
public T update(T t);
public void delete(T t);
}
For some reason, I can't make the implementation generic as well. Eclipse implements all interface methods in non-generic way:
public class BaseBeanImpl<T> implements NewBaseBean {
#Override
public Object create(Object t) {
return null;
}
#Override
public Object read(Long id) {
return null;
}
#Override
public Object update(Object t) {
return null;
}
#Override
public void delete(Object t) {
}
#Override
public Object find(Long id) {
return null;
}
}
When I change:
public Object create(Object t)
to
public T create(T t)
I get a compile error. Did I miss something?

Change
public class BaseBeanImpl<T> implements NewBaseBean
to
public class BaseBeanImpl<T> implements NewBaseBean<T>
When you use the raw type NewBaseBean, you get Object instead of T in your interface's methods.
public class BaseBeanImpl<T> implements NewBaseBean<T> {
#Override
public T create(T t) {
return null;
}
#Override
public T read(Long id) {
return null;
}
#Override
public T update(T t) {
return null;
}
#Override
public void delete(T t) {
}
#Override
public T find(Long id) {
return null;
}
}

Related

how to implement generic spring jpa repository for all entities

I have other BaseDaoImpl which is already generic but i want to add PaginationandSortiongRepository as generic, Please Help to Implement
I have tried every way to add GenericJPADAO as bean but its not possible is there, Is there any other way to implement?
public interface BaseDao<T, ID extends Serializable> {
public List<T> findAll();
public T findOne(final long id);
public T update(T object);
public T get(Long id);
public void delete(T object);
public void insert(T object);
public boolean exists(Long id);
T getByCondition(String fieldName, Object value);
List<T> getALL();
}
public class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> {
#PersistenceContext
protected EntityManager entityManager;
private Class<T> entityType;
public BaseDaoImpl() {
this.entityType = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
#Override
#Transactional
public void insert(T entity) {
entityManager.persist(entity);
}
#Transactional
public List<T> findAll() {
return entityManager.createQuery("from " + entityType.getName()).getResultList();
}
#Override
#Transactional
public T findOne(long id) {
return entityManager.find(entityType, id);
}
#Override
#Transactional
public T update(T entity) {
return entityManager.merge(entity);
}
#Override
#Transactional
public T get(Long id) {
// TODO Auto-generated method stub
return entityManager.find(entityType, id);
}
#Override
#Transactional
public void delete(T object) {
entityManager.remove(object);
}
#Override
#Transactional
public boolean exists(Long id) {
return entityManager.contains(id);
}
#Override
#Transactional
public T getByCondition(String fieldName, Object value) {
System.out.println(entityType);
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<T> criteria = cb.createQuery(entityType);
Root<T> member = criteria.from(entityType);
criteria.select(member).where(cb.equal(member.get(fieldName), value + ""));
List<T> results = entityManager.createQuery(criteria).getResultList();
if (results.isEmpty()) {
return null;
} else {
return (T) results.get(0);
}
}
#Override
public List<T> getALL() {
return null;
}}
#NoRepositoryBean
public interface GenericJpaDao<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
enter code here
}
#Repository
public class AccountDaoImpl extends BaseDaoImpl<Account, Long> implements AccountDao {
/* Not able to Inject If add #Repository on GenericJapDao, How to Implement As generic Same as BaseDaoImpl*/
GenericJpaDao< Account, Long> generiCJPADao;
#Override
public Account getAccount(String emailAddress) {
return getByCondition("emailAddress", emailAddress);
}
#Override
public void saveAccount(Account account) {
insert(account);
}}
Not able to add GenericJPA and i am not sure how to make Repository as Generic,
Thnaks in Advance

Uncheck conversion on returning class type

I have a method that returns a class type, and it is working right.
The problem is... I am getting some compilation warnings indicating unchecked conversion.
Below is the warning message I got:
Warning: java: getAjaxEventPayloadClass() in <anonymous com.iyotbihagay.wicket.panel.requestpage.resultlist.ResultList2$7> implements <P>getAjaxEventPayloadClass() in com.iyotbihagay.wicket.panel.paging.Paging.Support
return type requires unchecked conversion from java.lang.Class<com.iyotbihagay.wicket.support.RefreshSearchResultEventPayload> to java.lang.Class<P>
even if I use #SuppressWarnings("unchecked") I still cannot get rid of the compilation warning.
Below are some of the codes pointing to the warning:
ResultList2.java
public class ResultList2 {
...
private Component createPaging() {
return new Paging("paging", getRequestPageContext(), new Paging.Support() {
#Override
public void switchPage(AjaxRequestTarget target, int targetPageNum) {
getRequestPageContext().switchPage(target, targetPageNum);
}
#Override
public int getTotalNum() {
return getSearchResult().getTotalNum();
}
#Override
public int getPageSize() {
return getSearchResult().getPageSize();
}
#Override
public int getLastPageNum() {
return getSearchResult().getLastPageNum();
}
#Override
public int getCurrentPageNum() {
return getSearchResult().getCurrentPageNum();
}
#SuppressWarnings("unchecked")
#Override
public Class<RefreshSearchResultEventPayload> getAjaxEventPayloadClass() {
return RefreshSearchResultEventPayload.class;
}
#Override
public void decorateAjaxAttributes(AjaxRequestAttributes attributes, String pageNumMarkupId) {
decorateAjaxRefreshSearchResult(attributes, pageNumMarkupId);
}
});
}
...
}
Support.java
public static interface Support extends Serializable {
...
<P extends AjaxEventPayload> Class<P> getAjaxEventPayloadClass();
...
}
Paging.java
public class Paging {
...
private Support m_support;
...
#Override
public void onEvent(IEvent<?> event) {
super.onEvent(event);
WicketUtil.onEvent(event, m_support.getAjaxEventPayloadClass(), new AjaxEventHandler<AjaxEventPayload>() {
#Override
public void onEvent(IEvent<?> event, AjaxRequestTarget target, AjaxEventPayload paymentLoad) {
m_firstPageNumModel.detach();
m_previousPageNumModel.detach();
m_nextPageNumModel.detach();
m_lastPageNumModel.detach();
target.add(m_container);
}
});
}
...
}
WicketUtil.java
public class WicketUtil {
...
public static <P extends AjaxEventPayload> void onEvent(IEvent<?> event, Class<P> targetPayload, AjaxEventHandler<P> handler) {
if (event.getPayload() != null) {
if (targetPayload.isAssignableFrom(event.getPayload().getClass())) {
P p = (AjaxEventPayload)event.getPayload();
handler.onEvent(event, p.getTarget(), p);
}
}
}
...
}
m_support.getAjaxEventPayloadClass() is called/passed on WicketUtil.onEvent()... specifically on the second parameter.
RefreshSearchResultEventPayload is just one of the classes that extends AjaxEventPayload and there are other classes that extends to AjaxEventPayloadand are passed to WicketUtil.onEvent().
This should rather be:
public static interface Support extends Serializable {
...
Class<? extends AjaxEventPayload> getAjaxEventPayloadClass();
...
}
and
public class ResultList2 {
...
#Override
public Class<RefreshSearchResultEventPayload> getAjaxEventPayloadClass() {
return RefreshSearchResultEventPayload.class;
}
...
}
The reason is that <P extends AjaxEventPayload> means that the method can return a class of arbitrary payload type (as requested by the caller), e.g.:
support.<AjaxEventPayload>getAjaxEventPayloadClass()
instead of returning only the one payload type that is specific to the implementing class (e.g. RefreshSearchResultEventPayload).

How to generify my interface

I have the following interface:
public interface ProvidersFilter {
void setQuery(#NonNull Object query);
Object apply();
}
And the following implementing classes:
First implementation:
public class ProvidersRemoteFilter implements ProvidersFilter {
private Query mQuery;
#Override
public void setQuery(#NonNull Object query) {
if (query instanceof Query) {
mQuery = (Query) query;
} else {
throw new RuntimeException("query object must be of type com.google.firebase.firestore.Query");
}
}
#Override
public Object apply() {
return mQuery;
}
}
Second implementation:
public class ProvidersLocalFilter implements ProvidersFilter {
private String mQuery;
#Override
public void setQuery(#NonNull Object query) {
if (query instanceof String) {
mQuery = (String) query;
} else {
throw new RuntimeException("query object must be of type String");
}
}
#Override
public Object apply() {
return mQuery;
}
}
I would like to avoid using instanceof by generifying my interface and implementing classes.
You need to add a type variable to your interface.
Interface:
public interface ProvidersFilter<T> {
void setQuery(#NonNull T query);
T apply();
}
Implementing class:
public class ProvidersRemoteFilter implements ProvidersFilter<Query> {
private Query mQuery;
#Override
public void setQuery(#NonNull Query query) {
mQuery = query;
}
#Override
public Query apply() {
return mQuery;
}
}
Since local and remote Providers have the same code you could have an abstract class that implements the commonalities. In that case there is no need for the interface but you can keep it all the same:
public interface ProvidersFilter<Q> {
void setQuery(#NonNull Q query);
Q apply();
}
abstract class AbstractProvidersFilter<Q> {
private Q mQuery;
#Override
public void setQuery(#NonNull Q query) {
mQuery = query;
}
#Override
public Q apply() {
return mQuery;
}
}
public class ProvidersRemoteFilter extends AbstractProvidersFilter<Query> {}
public class ProvidersLocalFilter extends AbstractProvidersFilter<String> {}

Implementing a kotlin interface in java

So, after this question where I basically exploits reflection for passing primitive references to modify the primitive itself, like:
_begin("Another Window", ::showAnotherWindow)
I was looking for something to make something similar possible also from java, where at the moment I am using plains primitive arrays:
private boolean[] showAnotherWindow = {false};
imgui.begin("Another Window", showAnotherWindow);
#hotkey suggested me the possibility to create a class implementing the KMutableProperty0 interface and that automatically gets and sets the corresponding variable
Example:
KMutableProperty0<Boolean> prop =
PropUtils.javaProp(this, t -> t.showAnotherWindow, (t, r) -> { t.showAnotherWindow = r; });
_begin("Another Window", prop);
So, I wanted to give it a try and implemented the following in java.
Getter:
#FunctionalInterface
public interface Getter<T> {
T get();
}
Setter:
#FunctionalInterface
public interface Setter<T> {
void set(T type);
}
And then the class itself (I just wrote the constructor, all the methods are those requested by the interface and automatically implemented by the IDE) :
public class JavaProp <T> implements KMutableProperty0<T> {
private imgui.Getter<T> getter;
private imgui.Setter<T> setter;
public JavaProp(imgui.Getter<T> getter, imgui.Setter<T> setter) {
this.getter = getter;
this.setter = setter;
}
#Override
public void set(T t) {
setter.set(t);
}
#NotNull
#Override
public Setter<T> getSetter() {
return null;
}
#Override
public T get() {
return getter.get();
}
#Nullable
#Override
public Object getDelegate() {
return null;
}
#NotNull
#Override
public Getter<T> getGetter() {
return null;
}
#Override
public T invoke() {
return null;
}
#Override
public boolean isLateinit() {
return false;
}
#Override
public boolean isConst() {
return false;
}
#NotNull
#Override
public String getName() {
return null;
}
#NotNull
#Override
public List<KParameter> getParameters() {
return null;
}
#NotNull
#Override
public KType getReturnType() {
return null;
}
#NotNull
#Override
public List<KTypeParameter> getTypeParameters() {
return null;
}
#Override
public T call(Object... objects) {
return null;
}
#Override
public T callBy(Map<KParameter, ?> map) {
return null;
}
#Nullable
#Override
public KVisibility getVisibility() {
return null;
}
#Override
public boolean isFinal() {
return false;
}
#Override
public boolean isOpen() {
return false;
}
#Override
public boolean isAbstract() {
return false;
}
#NotNull
#Override
public List<Annotation> getAnnotations() {
return null;
}
}
But whenever I try to run that, I get the following:
Error:(45, 12) java: reference to Getter is ambiguous
both interface kotlin.reflect.KProperty0.Getter in kotlin.reflect.KProperty0 and interface kotlin.reflect.KProperty.Getter in kotlin.reflect.KProperty match
The problematic function is this one:
#NotNull
#Override
public Getter<T> getGetter() {
return null;
}
And the relevant file is kotlin.reflect.KProperty.tk, you can find it here
Any idea how could I solve it?
Just specify which interface you mean:
public KProperty0.Getter<T> getGetter()
But I would prefer to implement the class in Kotlin and only consume it from Java.

Not able to override method with generics

I have following methods defined in interface
public interface Stack<T> {
void method1(T element);
T method2();
}
Class Implementing this interface implements these methods as follows
private List<T> elements;
#Override
public void method1(T element) {
elements.add(element);
}
#Override
public T method2() {
return elements.remove(elements.size() - 1);
}
With this I get following error for method1: Method does not override method from super class, while method2 works fine.
Any idea what am I doing wrong?
This works perfectly fine:
import java.util.ArrayList;
import java.util.List;
public class Main {
interface MyStack<T> {
void push(T item);
T pop();
}
static class MyStackImpl<T> implements MyStack<T> {
private List<T> items = new ArrayList<T>();
#Override
public void push(T item) {
items.add(item);
}
#Override
public T pop() {
return items.remove(items.size() - 1);
}
}
public static void main(String[] args) {
MyStack<Integer> stack = new MyStackImpl<Integer>();
stack.push(42);
System.out.println(stack.pop());
}
}
You need to add type parameter to the interface and to the class too:
public interface Stack<T> { // here it is: <T>
void method1(T element);
T method2();
}
public class Impl<T> implements Stack<T> { // and here too
private List<T> elements;
#Override
public void method1(T element) {
elements.add(element);
}
#Override
public T method2() {
return elements.remove(elements.size() - 1);
}
}
You just need to specify the interface's generic type interface Stack<T>.
public interface Stack<T> {
void method1(T element);
T method2();
}
And you also need to define the generic type in you implementation class YourStack<T>
class YourStack<T> implements Stack<T>{
private List<T> elements;
#Override
public void method1(T element) {
elements.add(element);
}
#Override
public T method2() {
return elements.remove(elements.size() - 1);
}
}

Categories

Resources