Creating two generic parameters in an interface - java

I am trying to create a generic interface for my classes that will satisfy them all. I have created base classes to link them all together but the interface I'm trying to create isn't working like I'd expect it to and I cant find the right words to type into the search to find them.
The interface so far is:
public <T extends SDOBase> T entityToSDO(<? extends BaseEntity> entity, T sdo) throws Exception;
How do I make entity a second generic type?

Try declaring your method this way:
public <T extends SDOBase, E extends BaseEntity> T entityToSDO(E entity, T sdo) throws Exception;

I think you want something more along the lines of:
public interface MyInterface<T extends SDOBase>
{
public T entityToSDO(<? extends BaseEntity> entity, T sdo) throws Exception;
}

You just need
public <T extends SDOBase> T entityToSDO(BaseEntity entity, T sdo) throws Exception;
Anything that is an instance of a subtype of BaseEntity automatically is an instance of BaseEntity.

Related

How to check if a (type variable) Class<T> is implementing the Interface SomeInterface<T extends SomeInterface<T>>?

I'm working with JSON data and converting it into Java POJO class, then I built an interface like this:
public interface DataUtil<T extends DataUtil<T>> {
default T someDefaultFn() { ... };
}
And I used this interface for some POJO data class like:
public MyPoJo extends DataUtil<MyPojo> { ... }
And I get stuck when I to try check the type variable Class<FType> (a FieldType of any fields are declared inside T class) whether FType extends DataUtil<FType extends DataUtil<FType>> or not? I'm also trying to research the java.reflect package but did not find the expected answer. Can anyone help me to resolve this problem or find another design solution for this scenario?

Exception with generic set of ConstraintViolations

I am working on some service code that is using JSR-303 validation to test a request object. What I would like to do is throw a custom RuntimeException when the validation fails containing the Set of ConstraintViolations.
All of my request objects ultimately implement the same interface, lets call it Request. I think have an AbstractRequest that implements Request, and then a bunch of implementations of AbstractRequest, for instance MyRequest.
For the exception, what I am trying to do is something like:
public class RequestViolationException extends RuntimeException {
private Set<ConstraintViolation<? extends Request>> violations;
public <T extends Request> RequestViolationException(Set<ConstraintViolation<T>> newViolations) {
this.violations = newViolations;
}
}
And I am calling it like:
Set<ConstraintViolation<MyRequest>> violations = validator.validate(myRequest);
if (violations.size() > 0) {
throw new RequestViolationException(violations);
}
But this is not working. I have tried a few other variations on this theme, like making the constructor take a Set<ConstraintViolation<? extends Request>>, making violations a Set<ContraintViolation<Message>>, making violations a Set<ContraintViolation<Message>>, setting it to a HashSet<ContraintViolation<Message>> then iterating of newViolations, etc. Each has proven to give a myriad of different compiler errors. How can I have a Set of ContraintViolation<T> where <T> is some extension of Request and have it work?
You can't extend an exception with generics:
http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#cannotCatch
Actually #JGilardi is right, your constructor accepts <T extends Request> but you are trying to assign it to instance variable violations which is <? extends Request> which is illegal. Please refer to
http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html for a detailed explanation.
To parameterize the instance variable with the same <T extends Request> you have to parameterize the class which again extends RuntimeException and thus not parameterizable. :(

How do I bind a Generic class?

When I try to mock a Dao using Jukito I get the following exception:
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.jukito.JukitoModule.addKeyDependency(JukitoModule.java:338)
at org.jukito.JukitoModule.addInjectionPointDependencies(JukitoModule.java:330)
at org.jukito.JukitoModule.addDependencies(JukitoModule.java:313)
The object I try to mock is a ConcreteDao.
public class ConcreteDao extends AbstractDao<MyDomain> {
}
public abstract class AbstractDao<T extends DatastoreObject> {
}
I read several posts on SO about this binding generics but I can't figure out a way to use TypeLiteral for my binding.
This is what I tried:
bind(new TypeLiteral<AbstractDao<MyDomain>>(){}).to(ConcreteDao.class);
You need to bind like this:
bind(new TypeLiteral<AbstractDao<MyDomain>>(){}).to(new TypeLiteral<ConcreteDao<MyDomain>>(){});
This is how you can retrieve the generic class:
class AbstractDao {
protected final Class<T> clazz;
#Inject
public AbstractDao(TypeLiteral<T> type) {
clazz = (Class<T>) type.getRawType();
}
}
Subclasses of AbstractDao will need to pass entity specific TypeLiterals to the parent class (AbstractDao):
class ConcreteDao extends AbstractDao<MyDomain> {
#Inject
public ConcreteDao(TypeLiteral<MyDomain> type) {
super(type);
}
}
Note that you can make your AbstractDao class non-abstract and implement basic CRUD operations, so that you can use it without the need to extend AbstractDao for each entity. You will just need a binding for each entity like this:
bind(new TypeLiteral<GenericDao<User>>(){}).in(Scopes.SINGLETON);
See my blog-post for more information.

Which design pattern should be used in this use case?

I am working on app where I have to write custom validation on some xmlbean oject, basically to see so and so fields with proper values exist or not. Now those objects are generated from diff schema. I am using validation provided by xmlbeans against the schema but there are some more business validation needs to be done for these objects before it is being processed further.
Can somebody suggest any design pattern for this use case?
Thanks
Define your own validator interface:
interface Validator <T extends XmlBean> {
boolean validate(T bean);
}
Implement it for each classyou are dealing with, you can provide a factory class to get the validator for each bean class by implementing the following interface:
interface IValidatorFactory {
public <T extends XmlBean> Validator<T> getValidator(Class<T> clazz);
}
class ValidatorFactory implements IValidatorFactory {
private final Map<Class<? extends XmlBean>, Validator<? extends XmlBean>> map =
new HashMap<Class<? extends XmlBean>, Validator<? extends XmlBean>>();
#SuppressWarnings("unchecked")
#Override
public <T extends XmlBean> Validator<T> getValidator(Class<T> clazz) {
return (Validator<T>)map.get(clazz);
}
public <T extends XmlBean> void registerValidator(Class<T> clazz, Validator<T> validator) {
map.put(clazz, validator);
}
}
You could potentially add your own custom pre- and post-set hooks to your generated XmlBeans classes. To add add the hooks you need to create an .xsdconfig file and provide a some preSet() and postSet() static methods that can be called.
For an example, see:
https://www.ibm.com/developerworks/xml/library/x-xmlbeanse/?ca=dgr-eclipse-1
And also:
http://svn.apache.org/viewvc/xmlbeans/trunk/test/cases/xbean/extensions/prePostFeature/readOnlyBean/po.xsdconfig?revision=HEAD&view=markup
http://svn.apache.org/viewvc/xmlbeans/trunk/test/src/xmlobject/extensions/prePostFeature/readOnlyBean/existing/FooHandler.java?revision=HEAD&view=markup

java generic wildcards

Currently I'm working on a service interface which retrieves domain objects based on a primary key. However I get the feeling I'm not efficiently using generics.
Base domain objects look as follows:
public interface DomainObject<PK extends Serializable> extends Serializable {
PK getID();
}
My service interface looks as follows:
public interface LoadService<T extends DomainObject<PK>, PK extends Serializable> {
T load(PK ID);
}
This works, however I have to specify the PK type in the service generics, even though the PK type is already known inside T. Is there any way I can get around having to define my PK again in the LoadService interface? Something like:
LoadService<T extends DomainObject<? extends Serializable as PK> { ... }
Help will be greatly appreciated!
There is no way to avoid that because you use PK class at the 'LoadService'. I mean that you can define service like
interface LoadService<T extends DomainObject<?>> {
void store(T data);
}
However, that's not the option if you use PK class because compiler checks that PK type is compatible with the domain object type.
Another option is to remove type parameter from DomainObject, i.e. perform the following:
interface DomainObject extends Serializable {
Serializable getID();
}
Try using multiple bounds for the type parameter, if T both extends DomainObject and implements Serializable:
interface LoadService<T extends DomainObject<T> & Serializable> {
}

Categories

Resources