Annotation Arguments with Generics Class - java

I would like to understand of this issue
public class DogController extends FeedCommonController<DogModel extends CommonAnimalModel, FARMER_1_AUTH> {
// something
// This is working - but there is duplication
#Security.Authenticated(FARMER_1_AUTH.class)
public boolean feed_it() {
// nothing special
DogModel.getRandom().feed_it();
}
}
public class CatController extends FeedCommonController<CatModel extends CommonAnimalModel, FARMER_2_AUTH> {
// something
// This is working - but there is duplication
#Security.Authenticated(FARMER_2_AUTH.class)
public boolean feed_it() {
// nothing special
CatModel.getRandom().feed_it();
}
}
And I want to simplify the code and remove the duplicate methods, but I cannot put Class type to annotation.
public abstract class CommonAnimalController< T extends CommonAnimalModel, XXXXXX> {
#Security.Authenticated(XXXXXX.class) // <-- Here is a problem with declaration
public boolean feed_it() {
T.getRandom().feed_it();
}
}
/**
Get Token From HTTP Request from Actual Thread
*/
public class Security {
#With(AuthenticatedAction.class)
#Target({ElementType.TYPE, ElementType.METHOD})
#Retention(RetentionPolicy.RUNTIME)
public #interface Authenticated {
Class<? extends Authenticator> value() default Authenticator.class;
}
}
Concept with Annotation is already created and implemented on hundred classes. So its not possible make huge changes. But Its some Elegant way how to solved this?

You have two problems in one question.
First problem you have is: How to get a class instance of generics type T
This is answered here: How to get a class instance of generics type T
The second problem you have, is how to avoid passing a constant to the annotation. You will have a compliation error "Attribute value must be constant"
For this second problem seems there is no simple way to achieve it in Java. (pheraps I am wrong)
See this answer: How to supply value to an annotation from a Constant java
Solution for problem1
public abstract class CommonAnimalController<T extends CommonAnimalModel, XXXXXX> {
final Class<XXXXXX> typeParameterClass;
public CommonAnimalController(Class<XXXXXX> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
#Security.Authenticated(typeParameterClass) // you will have "Attribute value must be constant"
public boolean feed_it() {
return T.getRandom().feed_it();
}
}

Related

Generic method to return function returning generic self-type without the need to cast

Honestly, I'm not even sure whether that title makes sense. Hopefully the code following will explain the issue at hand.
package what.ever.you.like;
import java.util.function.UnaryOperator;
class SelfTypeTemplates {
public static <SELF extends AbstractSelfType> UnaryOperator<SELF> simpleBound() {
return self -> self;
}
public static <SELF extends AbstractSelfType<SELF>> UnaryOperator<SELF> boundWithGenericType() {
return self -> self;
}
}
class ConcreteSelfType extends AbstractSelfType<ConcreteSelfType> {
public ConcreteSelfType() {
super(ConcreteSelfType.class);
}
public ConcreteSelfType applySimpleBound() {
// How to get rid of the type cast?
return (ConcreteSelfType) SelfTypeTemplates.simpleBound().apply(this);
}
public ConcreteSelfType applyBoundWithGenericType() {
// Compile error because `this` is ConcreteSelfType, but required is SELF
return SelfTypeTemplates.boundWithGenericType().apply(this);
}
}
class AbstractSelfType<SELF extends AbstractSelfType<SELF>> {
protected final SELF myself;
protected AbstractSelfType(final Class<?> type) {
this.myself = (SELF) type.cast(this);
}
}
My issue is with the two methods applySimpleBound() and applyBoundWithGenericType().
The former is compiling fine, but needs explicit casting, which is what I'd like to get rid of.
The later does not compile, because .apply(this) requires a type SELF but provided is ConcreteSelfType.
So my question is, how do I specify the signature of a method in SelfTypeTemplates to return an UnaryOperator<SELF> so that invoking the returned function (.apply(this)), does not need casting in the client code (i.e. ContreteSelfType)?
Tried to play with different bounds in the generic and return type. Haven't found a working version without type casting.
Sometimes the compiler cannot infer the correct type for what ever reason. To work around this issue you can specify it like this:
class ConcreteSelfType extends AbstractSelfType<ConcreteSelfType> {
public ConcreteSelfType() {
super(ConcreteSelfType.class);
}
public ConcreteSelfType applySimpleBound() {
// How to get rid of the type cast?
return SelfTypeTemplates.<ConcreteSelfType>simpleBound().apply(this);
}
public ConcreteSelfType applyBoundWithGenericType() {
// Compile error because `this` is ConcreteSelfType, but required is SELF
return SelfTypeTemplates.<ConcreteSelfType>boundWithGenericType().apply(this);
}
}
Both options compile this way and you don't need a cast.

Extend a Java Enum with additional functions

I have an enum from a common Library (it cannot be changed) as a field from a Class.
I need to use that enum values as a switch-case in order to do something accordingly (for example save some data to a database).
This is for a Java 11 micro-service using Spring as a framework.
What I did before knowing the enum has to stay immutable, I avoided an ugly switch case with an overridden abstract function inside the enum like this:
public enum InvoiceStatus {
DRAFT {
#Override public void action(InputMessage inputMessage) {
invoiceFileService.draft(inputMessage);
}
},
VALID {
#Override public void action(InputMessage inputMessage) {
invoiceFileService.valid(eiInvoiceFileMessage);
}
},
NOT_VALID {
#Override public void action(InputMessage inputMessage) {
invoiceFileService.notValid(eiInvoiceFileMessage);
}
};
//+20 more values...
#Autowired
InvoiceFileService invoiceFileService;
public abstract void action(InputMessage inputMessage);
}
and I simply called the enum like this, so with different values from the enum the called function from the service would be different without writing a long switch-case.
invoice.getStatus().action(inputMessage);
Now the new requirement needs the enum to live inside a common library so it can refer to InvoiceFileService class which will be only local to my project.
I tried different options like HashMaps but the code went ugly and un-maintainable.
Is there a clean way to extend the simple enum (with only values definition) and add to it the abstract function to do stuff? maybe java 8 added some new way to do this.
You could create a wrapper enum.
public enum WrappedInvoiceStatus {
DRAFT(InvoiceStatus.DRAFT, this::someAction),
// other values
private WrappedInvoiceStatus(InvoiceStatus status, Action action) {
this.status = status;
this.action = action;
}
private interface Action { // can be one of Java default functional interfaces as well
void doSomething(InputMessage msg);
}
private void someAction(InputMessage msg) {
// behavior
}
// some plumbing required
}
Basically I’m suggesting using wrapping and lambda expressions or method references. The world of functional programming takes some getting used to. Not everyone is a fan. Your mileage may vary.
As others already said, you can not extend the enum at runtime.
But an enum can implement an interface.
So the basic idea is:
You make an interface with the action as sole abstract method:
public interface InvoiceAction {
void action(InputMessage message);
}
Your enum implements that interface
public enum InvoiceStatus implements InvoiceAction {
// ... no other changes needed
}
In all the cases where you only need to use the actual action, change InvoiceStatus to InvoiceAction. This is the most risky change. Make sure to recompile all code.
Because InvoiceAction only has one abstract method, it's a functional interface, and can be implemented with a lambda expression:
invoice.setStatus(msg -> ...);
This change is probably the most invasive change, but it might be the right thing to do - if you need a different action next time, you won't have the same problem as today.
Enum type is not extendable and implicitly final as specified in JLS:-
An enum declaration is implicitly final unless it contains at least one enum constant that has a class body (§8.9.1).
Hence a class could not extends an enum type. However you could use wrapper or adapter pattern to add additional behaviours/fields of the enum. For example:-
#Service
public class SimpleInvoiceFileService implements InvoiceFileService{
private final InvoiceStatus invoiceStatus;
public SimpleInvoiceFileService(InvoiceStatus status){
invoiceStatus = status;
}
#Override
public void draft(InputMessage input){
this.invoiceStatus.action(input);
}
#Override
public void valid(InputMessage input){
this.invoiceStatus.action(input);
}
// Add more methods to InvoiceFileService interface
// as required and override them here.
}
JLS Reference:-
https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.9

(JAVA Enums) - Anonymous class inside enum constant

Good day!
I have an interface which only implements one single method. I dont feel like making several class which all implement this one single method therefore I decided to use anonymous classes instead.
I use enums for certain static items, these enums have instances of my interface. However, when I try to make an anonymous class inside my enum constants my IDE (eclipse) literally tells me nothing (as if it is outside a code block).
My question is as follows: Can I use anonymous classes inside my enum constants?
If my text was unclear (Sorry im not english) please see the example below.
Code example
/**
* My Interface
*/
public interface IPotato {
public void eatPotato();
}
/**
* My enum class
*/
public enum PotatoEnum {
I_WANT_TO_EAT_POTATO(new IPotato() {
#Override
public void eatPotato() {
// Cant put code here.
} });
private IPotato _myAnonymousClass;
private PotatoEnum(IPotato anonymousClass){
this._myAnonymousClass = anonymousClass;
}
public IPotato getPotato(){
return _myAnonymousClass;
}
}
You could do that, it is a perfectly valid solution.
As a recommendation, make your enum implement your interface to make the code more readable:
public enum PotatoEnum implements IPotato{
I_WANT_TO_EAT_POTATO(){
#Override
public void eatPotato() {
// Cant put code here.
}},//more ENUMS ;
}
Simply yes
By doing this you are doing something like that:
I_WANT_TO_EAT_POTATO(An object of a virtual class that implments IPotato class);
same as :
I_WANT_TO_EAT_POTATO(Passing any parameter defined by constructor);
See Enum constants as an Inner Classes and you are passing them parameters of their construcors
You can to that. The reason of your mistake is that you have two public identifier (enum and interface) in single file . remove public from enum and it will work
public interface IPotato {
public void eatPotato();
}
enum PotatoEnum {
I_WANT_TO_EAT_POTATO(new IPotato() {
#Override
public void eatPotato() {
// Cant put code here.
}
});
private IPotato _myAnonymousClass;
private PotatoEnum(IPotato anonymousClass) {
this._myAnonymousClass = anonymousClass;
}
public IPotato getPotato() {
return _myAnonymousClass;
}
}

Java Generics Question

Alright, I thought I understood generics pretty well, but for some reason I can't get my head wrapped around why this doesn't work. I have two classes, or I should say that Google has two classes (I'm trying to implement their Contacts API). They have a ContactEntry class (abbreviated below):
package com.google.gdata.data.contacts;
public class ContactEntry extends BasePersonEntry<ContactEntry> {
public ContactEntry() {
super();
getCategories().add(CATEGORY);
}
public ContactEntry(BaseEntry<?> sourceEntry) {
super(sourceEntry);
}
}
I left off one or two methods, but nothing important, its really just an implementation of its parent class BasePersonEntry which has most of the important stuff that concerns a person entry abbreviated code below:
package com.google.gdata.data.contacts;
public abstract class BasePersonEntry<E extends BasePersonEntry> extends
BaseEntry<E> {
public BasePersonEntry() {
super();
}
public BasePersonEntry(BaseEntry<?> sourceEntry) {
super(sourceEntry);
}
public List<CalendarLink> getCalendarLinks() {
return getRepeatingExtension(CalendarLink.class);
}
public void addCalendarLink(CalendarLink calendarLink) {
getCalendarLinks().add(calendarLink);
}
public boolean hasCalendarLinks() {
return hasRepeatingExtension(CalendarLink.class);
}
}
Now... what I can't quite understand is if I do something like the following:
public void method1(StringBuilder sb, ContactEntry contact) {
if (contact.hasCalendarLinks()) {
for (CalendarLink calendarLink : contact.getCalendarLinks()) {
...
}
}
}
Everything works fine. It is able to interpret that getCalendarLinks returns a list of type CalendarLink. However, if I want to abstract this method and have my method use BasePersonEntry, like the following:
public void method1(StringBuilder sb, BasePersonEntry entry) {
if (entry.hasCalendarLinks()) {
for (CalendarLink calendarLink : entry.getCalendarLinks()) {
...
}
}
}
I get a compiler error:
incompatible types
found : java.lang.Object
required: com.google.gdata.data.contacts.CalendarLink
For the life of me I just can't understand why? The call to getCalendarLinks is the EXACT same method (via inheritance), its returning the EXACT same thing. Maybe it has to do with BasePersonEntry being an abstract class?
If anyone, can shed some light on this I would be very much obliged. If it helps you can find a full version of this source code hosted by Google here: Link To Google Library Download. I was attempting this with version 1.41.3 of their gdata-java libraries.
The problem with your new definition, is that it's using Raw type not Generic type.
As a result type is erased from everything, including getCalendarLinks and its signature is reduced to equivalent of List<Object> getCalendarLinks( )
To fix it, change declaration to:
public void method1(StringBuilder sb, BasePersonEntry<?> entry)
Note <?> after BasePersonEntry. This way it's generic type.
Also, you probably want to change the class generic declaration to
public abstract class BasePersonEntry<E extends BasePersonEntry<E> >
Without <E> your compiler ( or IDE ) will generate an unchecked warning.

Design question - java - what is the best way to doing this?

I have a design problem.
I have two data objects which are instances of say class A and class B.
A and B don't have any behavior - they are java beans with getters and setters.
I have a Validation interface and 10 implementations of it defining different Validations.
I would like to specify in my properties file which Validation applies to which class.
Something like this:
class A XYZValidation,ABCValidation
class B: ABCValidation, PPPValidation, etc
How do I write my Validation class so that it serves objects that are instances of Class A OR ClassB, or just about any other Class C that I might want to add in future?
interface Validation {
public boolean check(??);
}
> Just wanted to add this line to say thank you to all those who have responded to this post and to say that I am loving my time here on this amazing website. Stackoverflow rocks!
Have you thought about using annotations to mark the fields you want to validate in your bean?
If you have 10 different validations you could specify 10 annotations. Then mark the fields using annotations:
#ValideStringIsCapitalCase
private String myString;
#ValidateIsNegative
private int myInt;
With reflection API iterate through all the fields and see if they are marked, something like this:
public static <T> validateBean(T myBean) throws IllegalAccessException {
Field[] fields = myBean.getClass().getDeclaredFields();
// This does not take fields of superclass into account
if (fields != null) {
for (Field field : allFields) {
if (field.isAnnotationPresent(ValideStringIsCapitalCase.class)) {
field.setAccessible(true);
Object value = field.get(existingEntity);
// Validate
field.setAccessible(false);
}
}
}
}
An option would be to mark the whole class with the validator you want to use.
EDIT: remember to include annotation:
#Retention(RetentionPolicy.RUNTIME)
for your annotation interface.
EDIT2: please don't modify the fields directly (as in the example above). Instead access their getters and setters using reflection.
I've probably misunderstood the question but would something like this suffice:
public class ValidationMappings {
private Map<Class, Class<Validation>[]> mappings = new HashMap<Class, Class<Validation>[]>();
public ValidationMappings() {
mappings.put(A.class, new Class[]{XYZValidation.class, ABCValidation.class});
mappings.put(B.class, new Class[]{ABCValidation.class, PPPValidation.class});
}
public Class[] getValidators(Class cls) {
if (!mappings.containsKey(cls)) return new Class[]{};
return mappings.get(cls);
}
}
When you want to get the list of validators for a particular class, you would then call getValidators(Class cls) and iterate over each validator and create an instance of each and call your check method.
something like this maybe?
interface Validation {
public boolean check(Validatable x);
}
interface Validatable {
}
class A implements Validatable {
...
}
class Validator {
public boolean validateObject(Validatable x){
boolean validated = true;
... //read config file, check which validation classes to call
//for each validation class v in the config file:
if(!v.check(x)) validated = false;
return validated;
}
}
If you just want it to deal with any object then it'll be Object's that your interface
public boolean check(Object o);
Unless you want to use some marker interface to tag classes that are suitable for validation
Did you mean:
public interface Validation<T> {
boolean check(T object)
}
First of all, I'd use the following interface
interface Validator {
boolean isValid(Object object);
}
to implicitly document what the return value actually means.
Secondly, I'd suggest to document in the interface what behavior is expected if the Validator doesn't know how to handle the given instance.
interface Validator {
/**
* #return false if this validator detects that the given instance is invalid, true if the given object is valid or this Validator can't validate it.
*/
boolean isValid(Object object);
}
That way, you'd simply have a List of Validators that you could throw your objects at.
The performance impact of incompatible Validators should be negligible if they are implemented properly, e.g. with an early instanceof.
On a side note, I'd use a List of Validators instead of a Set so you can order them according to complexity. Put the cheap (performance-wise) Validators at the start of the List as an optimization.
You could then use a general piece of code for validation, e.g.
public class Validators {
public static boolean isValid(Object o, Collection<Validator> validators) {
for(Validator current : validators) {
if(!current.isValid()) return false;
}
return true;
}
}
Depending on your use-case it might be a good idea to return something different than boolean in your interface. If you need information about what is wrong, e.g. to display it, you'd need to return that info instead.
In that case it might be a good idea to keep the above loop running so you'll get all validation errors instead of only the first.
A Visitor pattern would solve this
Calling the Visitor Validator it's possible to have this:
public interface Validatable {
public boolean validate(Validator v);
}
public interface Validator {
public boolean validate(A a);
public boolean validate(B b);
}
public class A implements Validatable {
public boolean validate(Validator v){
return v.validate(this);
}
}
public class B implements Validatable {
public void validate(Validator v) {
return v.validate(this);
}
}
// Default validator just doesn't know how to
// validate neither A's, nor B's
public class GenericValidator implements Validator {
public boolean validate(A a) {
throw new UnsupportedOperationException("Cannot validate A");
}
public boolean validate(B b) {
throw new UnsupportedOperationException("Cannot validate B");
}
}
// since XYZValidation is supposed to run only on A's
// it only overrides A validation
public class XYZValidation extends GenericValidator {
public boolean validate(A a) {
// validate a
return isVAlid(a);
}
}
// since ABCValidation is supposed to run on A's and B's
// it overrides A and B validation
public class ABCValidation extends GenericValidator {
public boolean validate(A a) {
// validate a
return isVAlid(a);
}
public boolean validate(B b) {
// validate b
return isVAlid(b);
}
}
// since ABCValidation is supposed to run only on B's
// it overrides A only B validation
public class PPPValidation extends GenericValidator {
public boolean validate(B b) {
// validate b
return isVAlid(b);
}
}

Categories

Resources