Cannot annotate inherited variable issue. Best alternative - java

I have a class with a variable with validation annotation:
import javax.validation.constraints.NotNull;
public class Class_A {
#NotNull
private String name;
public getName() {
return name;
}
}
This class is used in a function:
public void myFunction(Class_A aObj) {
System.out.println(aObj.getName());
}
But now, I want to conditionally use the validation. I have searched and found that there is no way to conditionally check for the validation so I figured I will have to split the Class_A into two classes, one with validation (Class_A_Val) and one without validation (Class_A_NoVal).
By doing that, I can only think of below solutions for myFunction:
1) Duplicate myFunction, one for each class (Code duplication)
2) Create an abstract class with abstract method getName() and make other two classes inherit this abstract class so I can call myFunction(Abstract_Class_A)
3) Create an interface with method getName() and make other two classes implement this interface so I can call myFunction(Interface_Class_A)
Which is considered to be the best way and why? I am leaning towards #2.
Is there any other way to implement this?
Is there a way to annotate an inherited variable?

You can override the annotations by using xml configuration. More information here.

Related

Can I make same class for different uses and pass a string along with it for different JsonProperty

I want to have a class that can have different JsonProperty according to what I want to set.
Example:
public class common {
#JsonProperty("what I want")
private String s;
}
public class first {
#JsonProperty("first")
private List<Common> firstCommonList;
}
public class second {
#JsonProperty("second")
private List<Common> secondCommonList;
}
How can I have the JsonProperty for the common class as let's say "firstCommon" using the class first and "secondCommon" using the class second? Is there any way to do this or do I have to make separate classes for them and not just a common one?
Please help if you know. Thank you
To my knowledge this is not possible. Annotations require compile time constants and you are asking for it to be changed according to the runtime parent class type. I would go with two different classes unless the common attributes are really in huge number that justify having a common class.

Replace switch case: interface vs abstract class

I have a code that has a switch statement and want to improve the design.
There's the interface and the the abstract class way.
I want to know which way is better and why ?
I have the following class :
enum MovieChargeType {regular, new_release }
class Movie {
public MovieChargeType type;
public double get_price(){
switch (type){
case regular: //return regular price
case new_release : // return new_release price }
}
}
So I decided to improve the design using 2 ways:
1 Way - Interfaces
Interface MovieType{
public double get_price();
}
class RegularMovie implements MovieType{
public double get_price(){
// return regular price
}
}
class NewMovie implements MovieType{
public double get_price(){
// return new price
}
}
class Movie{
public MovieType type;
public double get_price(){
type.get_price();
}
}
2 Way - abstract classes:
abstract class Movie {
public MovieChargeType type;
public abstract double get_price();
}
class RegularMovie extends Movie{
public double get_price(){
// return regular price
}
}
class NewMovie extends Movie{
public double get_price(){
// return new price
}
}
I want to know which one is better in such case?
I've noticed that people tend to go with interfaces but can someone explain why?
I want to know which one is better in such case? I've noticed that people tend to go with interfaces but can someone explain why?
The inheritance dependency is the strongest of all dependencies, because your sub classes inherit all the dependencies that your parent classes have. E.g. if a parent class depends upon some library your sub class can only be used if that library is on the classpath. Maybe you faced a indirectly referenced from class file error sometime ago in your IDE. This error occures because of dependencies of your parent classes that are not on the compile classpath.
That's why most of the developers tend to use interfaces and keep the interface signature as easy as possible. I mean that you should not use any library classes in an interface's signature. Only use POJOs so that your interfaces only depend on pure Java and not depend upon other libraries.
Abstract classes can be very useful when you want to implement the template method pattern. The template method defines an abstract algorithm that can be extended by sub classes. They just override or implement abstract methods from the parent class. Abstract classes can implement behavior. So if there is a common behavior to all of your sub classes an abstract class might be good choice. But keep in mind that abstractions should be stable. If you have abstractions that change often all of your sub classes are affected. This problem can drammatically increase with each hierarchy level and make your code hard to maintain. A good rule is that the higher a class is in your hierarchy the more stable it must be.
Abstract classes allow you to define the default behaviour of certain methods which the subclasses can override. Interfaces only allow you to define the signature of the methods, so each implementation will be different.
If you would like some classes to have a default behaviour for a price, then use the abstract class design over the interface.

Notify superclass about subclass creation

Is there any way how to automatically send notification from subclass to superclass after subclass has been fully initialized i. e. after finishing subclass constructor?
MOTIVATION
Base class has to provide some default methods that are working with list of class fields. Since subclass fields are accessible in parent class only after subclass creation, base class can't read these subclass fields in base class constructor. One solution is to read subclass fields at the begining of each base method which need to process these fields. Due of slow reflection, it is better to use lazy-initialization.
I'm curious if there is some not widely known callback mechanism in Java that will allow to define some "subclass-created-callback" so I would be able to initialize these fields without using lazy-initialization to achieve better maintainability.
I know it is possible to track deallocation of an object e. g. via finalize() or ReferenceQueue so I want to know If there is something similar for object creation.
EXAMPLE
Suppose you want to create an database Entity class (I know there are ORM based solution for this, but this is only for illustration of similar problems) which will be able to generate SQL statements like CREATE TABLE, INSERT, UPDATE, DELETE based on entity's class fields. So base class would be responsible for reading of class fields and also for producing these statements. To create an entity one would need just to extend Entity and use some field annotations like #Column, #Id, #AutoIncrement, ...
class Entity {
public String getCreateTableStatement() {
// lazy-initialize list of class fields and produce statement...
}
public String getInsertPreparedStatement() {
// lazy-initialize list of class fields and produce statement...
}
// update, delete, ...
}
Example of subclass
public Person extends Entity {
#Id public int id;
#Column public String name;
}
AIM
To replace lazy initialization be another pattern that will help to reduce amount of repeated code. Ideally, subclass would not have to define anything else, only just "extends Entity".
It is a bit unclear what you're trying to do, but in general, many problems that have to do with object creation can be solved by using a factory method that encapsulates the creational process. This way, you can do more than you can achieve in a single constructor call:
public static MySubClass createSubClass() {
MySubClass subClass = new MySubClass();
subClass.baseClassMethodThatManipulatesFields();
return subClass;
}
Note that (as others have pointed out), inheritance might not be the best solution for your problem. The methods you list in Entity should probably be at the responsibility of the factory that uses reflection for initializing the class.
I am not asking why. If you want to do exactly like in you answer, then parent object has full access to it's children via constructor. Yes, I know that child object is not fully initialized at this time, but annotation informations is available at this step.
This is an example:
import org.apache.commons.lang3.reflect.MethodUtils;
import javax.persistence.Id;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.util.ArrayList;
import java.util.List;
public class Entity {
protected Entity() {
List<AccessibleObject> ids = getAccessibleObjectWithAnnotation(Id.class);
List<AccessibleObject> columns = getAccessibleObjectWithAnnotation(Column.class);
}
private List<AccessibleObject> getAccessibleObjectWithAnnotation(Class<? extends Annotation> cls) {
List<AccessibleObject> res = new ArrayList<>();
res.addAll(FieldUtils.getFieldsListWithAnnotation(getClass(), cls));
res.addAll(MethodUtils.getMethodsListWithAnnotation(getClass(), cls));
return res;
}
}

Java: new AbstractClass(){} What is this declaration called?

In my application there is an abstract class which is used multiple time as follows:
public class Myclass{
int amount;
String name;
public void printResultsFromDB(){
new MyabstractClass(name){
#Override
String getDataFromDB(){
//some implementation
}
};
}
}
public abstract MyabstractClass{
String name;
public MyabstractClass(String name){
this.name = name;
}
abstract String getDataFromDB();
void execute(){
//Some implementation
}
}
I want to know what line number 5 in code called?
I know we cannot instantiate an abstract class. Is this declaration called an anonymous class?
This is called an anonymous type in Java. It allows you to implement an interface or extend an abstract class without needing a named class for it.
This is especially useful if the interface or abstract class is implemented very often and creating a new class for each implementation would end up in a confusing mess of classes. A good example for this is Java's Runnable interface that simply allows to pass a void method to a method which takes no arguments.
You can find more on this here: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
It is a anonymous class which will allow you to implement an interface.
From the Oracle docs:
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface
HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you
implement an interface, there is no constructor, so you use an
empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
You're not instantiating an abstract class. It's an anonymous inner class that extends MyabstractClass. It still has to provide an implementation of any abstract methods.
It's meant for cases where you want to provide some custom implementation for one case but you don't expect to reuse it anywhere else.

Aspectj. Creating innter type methods in multiple classes

If I put:
public CountryState CountryState.find(long id) {
return (CountryState) findById(CountryState.class, id);
}
I'm creating a method find in the class CountryState.
Is there a way to create a method in several classes? Do I need to repeat the code for each class I want to create?
I know that with aspect I can make a class inherit from another, but, doing this, I can create one superclass because java doesn't accept multiple inheritance.
This 'pattern' is how you do it in AspectJ.
Declare an interface:
interface Holder {}
Make your intertype declarations on the interface:
public int Holder.getMeAnInt() {
return 42;
}
When you make a declaration like that on an interface you are providing a 'default implementation'. So the interface will now define getMeAnInt() and any implementations of Holder that do not implement getMeAnInt() will get the default implementation.
The final piece of the puzzle is then to use declare parents to specify which group of types implement your interface:
declare parents: #Anno * implements Holder;
So now, any type annotated with #Anno will implement Holder and have the getMeAnInt() method.
You can actually solve it without using AOP. You could just use OOP/OOD. There are two ways (I assume you want to write method once):
Create abstract base class with the method implementation and derive all classes from it. This not the best idea, actually.
Creating helper class that will implement your find() method and share it between classes (either using Dependency Injection, or just by coupling them tightly).
So if I understand it correctly, what you want actually is a generic method that will return instances of the target class:
public <T> find(long id, T targetClassObject) {
Class<? extends T> class = targetClassObject.getClass();
// do something i.e. call target method via reflection
}

Categories