(JAVA Enums) - Anonymous class inside enum constant - java

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

Related

Annotation Arguments with Generics Class

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

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 oop: Two extended classes that need to be called regardless of type

I can't get my head around the following OOP problem in java:
I have two classes which extend some basic library classes.
class myMovie extends Movie
{
int posi_x;
int posi_y;
...
myMovie(PApplet parent, String filename, int pposi_x, int pposi_y, float pangle, String player)
{
super(parent, filename);
...
}
int getFadeVal()
{
...
}
void fadeOut(int pms)
{
...
}
void fadeIn(int pms)
{
...
}
void exit()
{
...
}
}
class myImage extends PImage
{
// Will get a somehow similar implementation
}
This works as intended. But now I have a "main loop" which draws all of these different objects and therefore i want to simply call the methods of these classes without asking of which type the object next in list is.
For me that means i need some type of head class which contains either a myMovie or a myImage. Something like:
class AnimationObject
{
var child;
...
}
And then in the main loop just calling
AnimationObject[] ani_list;
foreach(AnimationObject ani in ani_list)
{
ani.draw();
}
Of course the problem is that Java doesn't know something like "var". I Could use Object, but then i'd have to always cast the type of the object in the main loop.
Which is the correct approach to this problem? I can't really understand all those Interfaces, Abstract Classes etc. in contrast to my exact problem.
Which is the preferred and correct way to do this?
}
Use a interface for this:
public interface AnimationObject {
void draw();
}
public class myImage extends PImage implements AnimationObject {
[...]
}
public class myMovie extends Movie implements AnimationObject {
[...]
}
And in your main loop use the interface:
AnimationObject[] ani_list;
foreach(AnimationObject ani : ani_list) {
ani.draw();
}

how to inject interface to class in java?

i have my DTO class that is :
public class EmailResponse {
// Make public to avoid getters and setters
public Email email;
public RequestData reqData;
public EmailResponse() {
super();
}
}
and i want to implement to it this interface:
public interface IAssertionErrorDo {
public void onErrorDo();
}
but i want to do it during execution, i don't want to touch "EmailResponse" because it would not be ok to make it implements that interface due they don't belong to the same layer, i mean, EmailResponse would belong to service layer and IAssertionError would belong to test layer. I am using TestNG.
Do you know how i could do this? Regards
EDIT:
My implementation is this:
EmailResponse emailResponse = emailService.getUserEmail(userId);
And the reason i want to do this "injection" is because i have
public class LoggingAssert
extends Assertion {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAssert.class);
private IAssertionErrorDo dataE;
#Override
public void onAssertFailure(IAssert a, AssertionError ex) {
LOGGER.info("[ERROR] " + a.getMessage());
if (this.dataE != null) {
this.dataE.onErrorDo();
}
}
public LoggingAssert setOnErrorDo(IAssertionErrorDo object) {
this.object = object;
return this;
}
}
loggingAssert.setOnErrorDo(emailResponse).assertNotNull(emailResponse.getEmail().getId(),
"Checking created email doesn't exists");
So i want to if assert fails execute method onErrorDo() from emailResponse
You could do
public class MyEmailResponse extends EmailResponse implements IAssertionErrorDo {
...
}
implementation calls in interfaces, you can call more than 1 interface if you want by adding commas to separate them..
to call interface methods you simply just use the method's name.
like this:
public class MyEmailResponse implements IAssertionErrorDo
{
public void onErrorDo() {//define it's behavior}
}
if you extend a class you use:
super.MyMethod()
to call the a method inside the extended class, but if you already have an extended class and want a method from another class you have to create an object for that class first then call it, thus:
MyClass mc = new MyClass();
if it is in a different package then
myPackage.MyClass mc = new myPackage.MyClass();
then you call your method from that class using the object you created, which is in this case mc.. so:
mc.MyMethod();
if you want it to return a variable then you will need to add a return statement in that method with the variable you want it to return.
interfaces are usually used for global an changing environments (dynamics), for example if you developed a program and it needs a driver to connect to databases then you will make an interface and send it to the database developers, and each one will fill the codes in that interface and send it back... this guarantees consistency.
when you implement an interface you have to define every method inside it (even if you leave it empty) and you cannot change the interface's methods names nor add... it is used in other areas as well, i don't think you need to use it in your case.

What is the Best Way to Extend Functionality?

I've run into a situation in which I was to extend the functionality of a given class, but I'm not sure of the best way to go about this. I started by invoking functionality "upwards" and have now switched to "downwards", but I see issues with both. Let me explain what I mean. First, the "upwards" approach:
public class ParentValidator
{
public void validate() {
// Some code
}
}
public class ChildValidator extends ParentValidator
{
#Override
public void validate() {
super.validate();
// Some code
}
}
public class GrandchildValidator extends ChildValidator
{
#Override
public void validate() {
super.validate();
// Some code
}
}
This functions perfectly well, but it requires that I always remember to place super.validate() in my method body or the logic in the parent class(es) won't be executed. In addition, extension in this manner can be considered "unsafe" due to the fact that a child class could actually replace/modify the code defined in the parent class. This is what I call invoking methods "upwards" because I'm invoking methods from higher level classes as I go.
To counter these shortfalls, I decided to make ParentValidator.validate() final and have it invoke a different method. Here's what my code was modified to:
public class ParentValidator
{
public final void validate() {
// Some code
subValidate();
}
protected void subValidate() {}
}
public class ChildValidator extends ParentValidator
{
#Override
public final void subValidate() {
// Some code
subSubValidate();
}
protected void subSubValidate() {}
}
public class GrandchildValidator extends ChildValidator
{
#Override
public void subSubBalidate() {
// Some code
subSubSubValidate();
}
protected void subSubSubValidate();
}
This is what I was referring to when I say that I'm calling downwards as each class invokes methods on classes "down" the inheritance chain.
Using this approach, I can be guaranteed that the logic in the parent class(es) will be executed, which I like. However, it doesn't scale well. The more layers of inheritance I have, the uglier it gets. At one level, I think this is very elegant. At two levels, it starts to look shoddy. At three or more, it's hideous.
In addition, just as I had to remember to invoke super.validate() as the first line of any of my children's validate methods, I now have to remember to invoke some "subValidate" method at the end of any of my parent's validate methods, so that didn't seem to get any better.
Is there a better way to do this type of extension that I haven't even touched on. Either of these approaches have some serious flaws and I'm wondering if there's a better design pattern I could be using.
In what you describe as your first approach you are using simple inheritance, your second approach is closer to what the Gang of Four [GoF] called a Template Method Pattern because your parent class is using the so-called Hollywood Principle: "don't call us, we'll call you".
However, you could benefit from declaring the subvalidate() method as abstract in the parent class, and by this, make sure all subclasses are forced to implement it. Then it would be a true template method.
public abstract class ParentValidator
{
public final void validate() {
//some code
subValidate();
}
protected abstract void subValidate() {}
}
Depending on what you are doing there are other patterns that could help you do this in a different manner. For instance, you could use a Strategy Pattern to peform the validations, and by this favoring composition over inheritance, as suggested before, but a consequence is that you will need more validation classes.
public abstract class ParentValidator
{
private final ValidatorStrategy validator;
protected ParentValidator(ValidatorStrategy validator){
this.validator = validator;
}
public final void validate() {
//some code
this.validator.validate();
}
}
Then you can provide specific validation strategies for every type of Validator that you have.
If you want to get the best of both worlds you might considering implementing the solution as a Decorator Pattern where subclasses can extend the functionality of a parent class and still stick to a common interface.
public abstract class ValidatorDecorator implements Validator
{
private final Validator validator;
protected ParentValidator(Validator validator){
this.validator = validator;
}
public final void validate() {
//some code
super.validate(); //still forced to invoke super
this.validator.validate();
}
}
All patterns have consequences and advantages and disadvantages that you must consider carefully.
I'd prefer to 1) program against interfaces, and 2) opt for composition over inheritance. This is how I have done. Some people like it, some do not. It works.
// java pseudocode below, you'll need to work the wrinkles out
/**
* Defines a rule or set of rules under which a instance of T
* is deemed valid or invalid
**/
public interface ValidationRule<T>
{
/**
* #return String describing invalidation condition, or null
* (indicating then that parameter t is valid */
**/
String apply(final T t);
}
/**
* Utility class for enforcing a logical conjunction
* of zero or more validatoin rules on an object.
**/
public final class ValidatorEvaluator
{
/**
* evaluates zero or more validation rules (as a logical
* 'AND') on an instance of type T.
**/
static <T> String apply(final T t, ValidationRule<T> ... rules)
{
for(final ValidationRules<T> v : rules)
{
String msg = v.apply(t);
if( msg != null )
{
return msg; // t is not valid
}
}
return null;
}
}
// arbitrary dummy class that we will test for
// i being a positive number greater than zero
public class MyFoo
{
int i;
public MyFoo(int n){ i = n; }
///
}
public class NonZeroValidatorRule implements ValidatorRule<MyFoo>
{
public String apply(final MyFoo foo)
{
return foo.i == 0 ? "foo.i is zero!" : null;
}
}
// test for being positive using NonZeroValidatorRule and an anonymous
// validator that tests for negatives
String msg = ValidatorEvaluator.apply( new MyFoo(1),
new NonZeroValidatorRule(),
new ValidatorRule<MyFoo>()
{
public String apply(final MyFoo foo)
{
return foo.i < 0 ? "foo.i is negative!" : null;
}
}
);
if( msg == null )
{
\\ yay!
...
}
else
{
\\ nay...
someLogThingie.log("error: myFoo now workie. reason=" + msg );
}
More complex, non-trivial evaluation rules can be implemented this way.
The key here is that you should not use inheritance unless there exists a is-a relationship. Do not use it just to recycle or encapsulate logic. If you still feel you need to use inheritance, then don't go overkill trying to make sure that every subclass executes the validation logic inherited from the superclass. Have implementations of each subclass do an explicit execution on super:
public class ParentValidator
{
public void validate() { // notice that I removed the final you originally had
// Some code
}
}
pubic class ChildValidator extends ParentValidator
{
#Override
public void validate() {
// Some code
super.validate(); // explicit call to inherited validate
// more validation code
}
}
Keep things simple, and don't try to make it impossible or fool-proof. There is a difference between coding defensively (a good practice) and coding against stupid (a futile effort.) Simply lay out coding rules on how to subclass your validators. That is, put the onus on the implementors. If they cannot follow the guidelines, no amount of defensive coding will protect your system against their stupidity. Ergo, keep things clear and simple.
I prefer to using composition over inheritance if your subSubSubValidate is related general functionality. You can extract new class and move it there than you can use it without inheritance in the other classes.
There is also
"Favor 'object composition' over
'class inheritance'." (Gang of Four
1995:20)
maybe a look at the visitor pattern may help you to develop your pattern.
Here are some information on it : http://en.wikipedia.org/wiki/Visitor_pattern

Categories

Resources