How does Java implements the methods declared in the Annotations (Metadata)? - java

An image taken from a book which I am going through,
The caption says it all. Please suggest or give me something as to what happens behind the scenes.
For example, how does #NotNull in Hibernate Bean Validation API works?
I know that through Reflection API, we can do something like this,
class Meta {
// Annotate a method.
#MyAnno(str = "Annotation Example", val = 100)
public static void myMeth() {
Meta ob = new Meta();
// Obtain the annotation for this method
// and display the values of the members.
try {
// First, get a Class object that represents
// this class.
Class c = ob.getClass();
// Now, get a Method object that represents
// this method.
Method m = c.getMethod("myMeth");
// Next, get the annotation for this class.
MyAnno anno = m.getAnnotation(MyAnno.class);
// Finally, display the values.
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}

Annotations don't have any implemented code and actually don't do anything themself.
To make them "work", there should be some kind of annotation processor (initializer, loader or any class that works with annotated objects). This annotation processor checks annotation objects annotations and changes the way it is handled.
For example Spring annotation processor, when initializing an object, looks for #Autowired fields, to fill autowired fields.
Same goes for Hibernates #NotNull. it doesn't do anything actually. However, Hibernate, when persisting your object, checks if there should be something there.

Related

Calling private methods of a proxied outer bean by inner bean leads to NullPointerException on accessing outer bean property

First, about the problem I try to solve.
Imagine there is an EntityPersistentAdapter which works with some abstraction over SQL (querydsl is used in my case). This adapter implements many CRUD operations related to entity, operations are split into many interfaces (i.e. DeleteEntityDataPort), but implemented by a single adapter class since they have something in common (usually the same predicates on where-clause among different operations). For one operation I would like to have a dry-run implementation to evaluate how much data will be removed and report back to user before actual removal. I could use a transaction and rollback on dry-run, but decided to implement it in even more safer manner by executing select count instead of delete + rollback. To execute select count I need exactly the same set of where-conditions which I use for delete, so I extracted those conditions to a separate private method. To not expose this implementation detail method and reuse it at the same time, I decided to use inner class bean (or nested + outer class injection).
Let's look at the code. I composed an example which will be easy to reproduce with fresh start.spring.io project:
// DeleteEntityDataPort.java
public interface DeleteEntityDataPort {
long deleteDataForEntity(long entId);
}
// EntityPersistentAdapter.java
#Repository
public class EntityPersistentAdapter implements DeleteEntityDataPort {// actually implements many more fine-graned interfaces
private final Sql sql;
public EntityPersistentAdapter(Sql sql) {
this.sql = Objects.requireNonNull(sql);
}
#Override
public long deleteDataForEntity(long id) {
return sql.delete(commonConditionForBothDeleteAndDryRunSelectCount());
}
private int commonConditionForBothDeleteAndDryRunSelectCount() {
return 42;
}
// ....
#Repository
public /*static*/ class DryRunDeleteEntityData implements DeleteEntityDataPort {
// final EntityPersistentAdapter outerClassInstance;
//
// DryRunDeleteEntityData(EntityPersistentAdapter topLevel) {
// this.outerClassInstance = topLevel;
// }
//
// #Override
// public long deleteDataForEntity(long entId) {
// return outerClassInstance.sql.recordsCountSelect(
// outerClassInstance.commonConditionForBothDeleteAndDryRunSelectCount()
// );
// }
#Override
public long deleteDataForEntity(long entId) {
return sql.recordsCountSelect(
commonConditionForBothDeleteAndDryRunSelectCount()
);
}
}
}
// Sql.java
/* Sql abstaction stub
* #param condition represented by integer in both cases for simplicity, it does not matter
*/
#Component
public class Sql {
private static final long RECORDS_AFFECTED_HARDCODED_STUB = 42;
public long delete(int condition) {
System.out.println("Dangerous sql delete by condition " + condition + " executed, returning number of affected records");
return RECORDS_AFFECTED_HARDCODED_STUB;
}
public long recordsCountSelect(int condition) {
System.out.println("Safe select count by condition " + condition + " executed");
return RECORDS_AFFECTED_HARDCODED_STUB;
}
}
// test
#SpringBootTest
class NestedJavaBeanApplicationTests {
#Autowired
private EntityPersistentAdapter.DryRunDeleteEntityData dryRunComponent;
#Test
void contextLoads() {
dryRunComponent.deleteDataForEntity(1);
}
}
Notice the commented code for turning inner class into static nested one. The NPE problem is the same in both cases.
java.lang.NullPointerException: Cannot invoke "com.example.nestedjavabean.beans.Sql.recordsCountSelect(int)" because "this.this$0.sql" is null
at com.example.nestedjavabean.beans.EntityPersistentAdapter$DryRunDeleteEntityData.deleteDataForEntity(EntityPersistentAdapter.java:42)
The error I get is a NullPointerException on attempt to get outer class property (sql) from inner/nested class. That's because inner/nested class has access not to an instance of EntityPersistentAdapter, but to it's proxy. The problem only exists when my bean needs to be proxied (i.e. if I change #Repository to #Component on outer bean class the problem goes away, but in my real code I need my beans to be proxied).
Is there a way to solve the NPE problem without changing the structure of my code? Somehow force-inject non-proxy bean into nested class? If not, what would be the best alternative to achieve my goal? (reuse private condition method and do not expose implementation details)
Another option I thought of was to abstract away commonConditionForBothDeleteAndDryRunSelectCount and related code to a base class with protected visibility and then make my implementation classes to inherit it. But I wanted to avoid inheritance, since I do not see a clear 'is-a' relationship here.
You may also ask me why I try to use nested class to access private method instead of making a conditions method package-private. The answer is: I actually use Kotlin which does not have package-private visibility modifier.

How to pass model attributes globally to avoid repeatable code in Spring controller?

I would like to ask you for some best practice to reduce the amount of repeatable code in my controller's methods - one of them is presented below.
I have quite a big and complex view with a lot of information and two forms. In every method of my controller (and there are quite a few) I have to pass the same attributes to my view (in post controllers even twice). I added a note SAME CODE in the code snippet below indicating identical pieces of code.
I wonder if there is any possibility to make a one global method in the controller gathering all attributes to be passed to the model and just reference it in any of particular methods?
I looked into ModelAndView or ModelMap, but cannot see those being suitable here.
Just want to avoid repeating this part:
Repeatable piece of code
model.addAttribute("hotels", hotelService.getAllHotels());
List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
model.addAttribute("rooms", roomsDto);
model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
Full method with that piece of code appearing twice
#PostMapping("/hotels/{hotelId}/rooms")
public String createRoomForHotelById(#ModelAttribute("room") #Valid NewRoomDto roomDto,
BindingResult result,
#PathVariable("hotelId") Long hotelId,
Model model) {
if(result.hasErrors()) {
// SAME CODE
model.addAttribute("hotels", hotelService.getAllHotels());
List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
model.addAttribute("rooms", roomsDto);
model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
//
model.addAttribute("hotel", new NewHotelDto());
LOG.info("Binding error: {}", result.toString());
return "admin/dashboard";
}
// SAME CODE
model.addAttribute("hotels", hotelService.getAllHotels());
List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
model.addAttribute("rooms", roomsDto);
model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
//
LOG.info("AdminController: CreateRoomForHotelById: Created room: {}", roomDto.toString());
roomDto.setHotelId(hotelId);
roomService.createNewRoom(roomDto);
return "redirect:/auth/admin/hotels/{hotelId}/rooms";
}
You can also move the code from J Asgarov's answer into the same controller instead of another class annotated with #ControllerAdvice. That way that code will only be executed for #RequestMapping methods within that controller.
For multiple values you could also do something like this:
#ModelAttribute
public void foo(Model model, #PathVariable(required = false) Long hotelId) {
model.addAttribute("hotels", hotelService.getAllHotels());
if (hotelId != null) {
List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
model.addAttribute("rooms", roomsDto);
}
model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
}
But seeing your code I would rather suggest you move the repeated code into a private method and call it whenever you need those inside your model.
Your method createRoomForHotelById for example causes a redirect, which basically discards everything you put in your model.
For global model attributes you can use #ControllerAdvice:
Create a class and annotate it with #ControllerAdvice.
Inside of that class pass the model attribute (which will now be available globally) like so:
#ModelAttribute("foo")
public Foo foo() {
return new Foo();
}

Java annotation to set field to a static instance?

I've been playing with annotations, and I'm wondering how to go about doing this. What I'd like to do is to be able to have a field declared in a class and annotated such that the field will be initialized with a static instance of the class.
Given an annotation like this:
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME) //or would this be RetentionPolicy.CLASS?
public #interface SetThisField {
}
Something like this:
public class Foo {
#SetThisField
private Bar bar;
}
I've played around with using a parser and setting this at runtime, which works but isn't as elegant as I'd like.
I can't find any really good examples of RetentionPolicy.CLASS but the documentation seems to indicate that I could somehow make the declaration of "bar" get compiled into this:
private Bar bar = Bar.getInstance();
It wouldn't look that way in the source code of course, but it would in the byte code and it would behave like that at runtime.
So am I off base here? Is this possible? Or is the parser the way to go with it?
UPDATE: This is the guts of the parser I'm using
public static void parse(Object instance) throws Exception {
Field[] fields = instance.getClass().getDeclaredFields();
for (Field field : fields) {
//"Property" annotated fields get set to an application.properties value
//using the value of the annotation as the key into the properties
if (field.isAnnotationPresent(Property.class)) {
Property property = field.getAnnotation(Property.class);
String value = property.value();
if (!"".equals(value)) {
setFieldValue(instance, field, properties.getProperty(value));
}
}
//"Resource" annotated fields get static instances of the class allocated
//based upon the type of the field.
if (field.isAnnotationPresent(Resource.class)) {
String name = field.getType().getName();
setFieldValue(instance, field, MyApplication.getResources().get(name));
}
}
}
private static void setFieldValue(Object instance, Field field, Object value) throws IllegalAccessException {
boolean accessibleState = field.isAccessible();
field.setAccessible(true);
field.set(instance, value);
field.setAccessible(accessibleState);
}
I would suggest doing the replacement at run time. This is much simpler to implement and test. Changing the byte code at build time is relatively error prone and tricky to get right. For example you would need to understand how byte code is structured and in this case how to add the code to all the constructors in the right place in the code.
If you make the retention RUNTIME, you can have a library which examines the annotation and sets the value after the object is created.

Is this a good pattern for annotation processing?

I've got a fairly standard Spring webapp, and I have a number of custom annotations that I would like to use to denote the requirements and constraints applied to a given web-service method. For instance, I might apply an #RequiresLogin annotation to any method that requires a valid user session, and #RequiresParameters(paramNames = {"name", "email"}) on a method that requires that "name" and "email" be set, and so on.
In support of this I implemented an ad-hoc utility for validating a method's annotated constraints at runtime, which basically followed a pattern of:
Map<Class<? extends Annotation>, Annotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
if (annotations.containsKey(AnnotationType1.class)) {
AnnotationType1 annotation = (AnnotationType1)annotations.get(AnnotationType1.class);
//do validation appropriate to 'AnnotationType1'
}
if (annotations.containsKey(AnnotationType2.class)) {
AnnotationType2 annotation = (AnnotationType2)annotations.get(AnnotationType2.class);
//do validation appropriate to 'AnnotationType2'
}
//...
This works fine, but has become a bit unwieldy as I have added additional annotations. I'd like to replace it with something a bit more maintainable. Ideally I'd like to be able to do:
List<ValidatableAnnotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
for (ValidatableAnnotation annotation : annotations) {
annotation.validate(request);
}
But I'm pretty sure that is not possible since annotations themselves cannot contain executable code and since the compiler will not let me extend java.lang.annotation.Annotation (not that I'd know how to go about allowing executable code to be contained in an annotation even if the compiler let me try).
What annotations can contain, however, is a nested inner class, and that inner class can do anything that a normal Java class can do. So what I've come up with based upon that and in the interest of keeping my validation code as closely associated with the annotation being validated as possible is:
public interface AnnotationProcessor {
public boolean processRequest(Annotation theAnnotation, HttpServletRequest request);
}
And then the annotations can be implemented like:
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.TYPE})
public #interface RequiresLogin {
public static class Processor implements AnnotationProcessor {
#Override
public boolean processRequest(Annotation theAnnotation, HttpServletRequest request) {
if (! (theAnnotation instanceof RequiresLogin)) {
//someone made an invalid call, just return true
return true;
}
return request.getSession().getAttribute(Constants.SESSION_USER_KEY) != null;
}
}
}
Which keeps the validation logic nice and tightly coupled with the annotation that is being validated. Then all my ad-hoc validation code can be replaced with:
List<Annotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
for (Annotation annotation : annotations) {
processAnnotation(annotation, request);
}
private static boolean processAnnotation(Annotation annotation, HttpServletRequest request) {
AnnotationProcessor processor = null;
for (Class<?> processorClass : annotation.annotationType().getDeclaredClasses()) {
if (AnnotationProcessor.class.isAssignableFrom(processorClass)) {
try {
processor = (AnnotationProcessor)processorClass.newInstance();
break;
}
catch (Exception ignored) {
//couldn't create it, but maybe there is another inner
//class that also implements the required interface that
//we can construct, so keep going
}
}
}
if (processor != null) {
return processor.processRequest(annotation, request);
}
//couldn't get a a processor and thus can't process the
//annotation, perhaps this annotation does not support
//validation, return true
return true;
}
Which leaves no more ad-hoc code that needs to be revised every time I add a new annotation type. I just implement the validator as part of the annotation, and I'm done.
Does this seem like a reasonable pattern to use? If not then what might work better?
You may want to investigate AOP. You can advise methods that expose certain annotations and perform pre/post processing accordingly.
I would just like to add that while AOP would be a good solution, the Spring framework already provides this functionality by way of the #Secured annotation.
#Secured("ROLE_USER")
public void foo() {
}
Spring also supports JSR-303 validation with the #Valid annotation. So for these use cases at least, it seems you are re-inventing the wheel.
IMHO one could think about the Visitor pattern in combination with a factory. The factory will return a wrapper object that knows the exact annotation type and which the visitor will be able...
class MyVisitor {
public void visit(VisitableAnnotationType1 at) {
//something AnnotationType1 specific
}
public void visit(VisitableAnnotationType2 at) {
//something AnnotationType2 specific
}
... // put methods for further annotation types here
}
class VisitableFactory {
public abstract class VisitableAnnotation {
public abstract void accept(MyVisitor visitor);
}
class VisitableAnnotationType1 implements VisitableAnnotation {
public void accept(MyVisitor visitor) {
visitor.visit(this);
}
}
public static VisitableAnnotation getVisitable(Annotation a) {
if(AnnotationType1.class.isAssignableFrom(a.getClass()) {
//explicitely cast to the respective AnnotationType
return new VisitableAnnotationType1((AnnotationType1)a);
} else if (AnnotationType2.class.isAssignableFrom(a.getClass()) {
//explicitely cast to the respective AnnotationType
return new VisitableAnnotationType1((AnnotationType1)a);
}
}
}
As we cannot extend Annotation, we need those wrapper classes in the factory. You could also pass the original annotation which is then contained in that wrapper class.
What you have to do: For each new AnnotationType add a new "wrapper" class to the factory, extend the factory's
getVisitable()
method accordingly and also add an according method to the Visitor:
public void doSomething(VisitableAnnotationTypeXYZ at) {
//something AnnotationTypeXYZ specific
}
now the generic validation (or whatever) code looks like:
List<ValidatableAnnotation> annotations = mergeConstraintsFromClassAndMethod(serviceClass, serviceMethod);
MyVisitor visitor = new MyVisitor();
for (ValidatableAnnotation annotation : annotations) {
VisitableFactory.getVisitable(annotation).accept(visitor);
}
The visiting works by the indirection that the visited object calls the visitor with itself as the argument and thus the correct visit method will be invoked.
Hope that helps ;-)
Code is not tested, though...

How do app servers inject into private fields?

I saw this question
Inject into private, package or public field or provide a setter?
about how to manually inject into annotated private fields (The way is adding setters
or through a constructor)
But, the point is how do an application server (like glassfish, axis2, jboss, ...)
is able to inject into a final private field (without adding setters or constructors
to the user class)?
Quoting the cited question:
public SomeClass {
#Inject
private SomeResource resource;
}
Do they use a customized JVM (not the standard one) that allows to access private fields?
Thanks
It's a simple reflection "trick". It relies on the Field.setAccessible() method to force the member to be accessible programmatically:
Set the accessible flag for this
object to the indicated boolean value.
A value of true indicates that the
reflected object should suppress Java
language access checking when it is
used. A value of false indicates that
the reflected object should enforce
Java language access checks.
The Reflection API is used to get a handle on the field, setAccessible() is called, and then it can be set by the injection framework.
See an example here.
No magic, no custom VM.
With the help of skaffman I coded this simple example on how to inject without setters.
Perhaps it helps (It did to me)
//......................................................
import java.lang.annotation.*;
import java.lang.reflect.*;
//......................................................
#Target(value = {ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
#interface Inject {
}
//......................................................
class MyClass {
#Inject
private int theValue = 0;
public int getTheValue() {
return theValue;
}
} // class
//......................................................
public class Example {
//......................................................
private static void doTheInjection(MyClass u, int value) throws IllegalAccessException {
Field[] camps = u.getClass().getDeclaredFields();
System.out.println("------- fields : --------");
for (Field f : camps) {
System.out.println(" -> " + f.toString());
Annotation an = f.getAnnotation(Inject.class);
if (an != null) {
System.out.println(" found annotation: " + an.toString());
System.out.println(" injecting !");
f.setAccessible(true);
f.set(u, value);
f.setAccessible(false);
}
}
} // ()
//......................................................
public static void main(String[] args) throws Exception {
MyClass u = new MyClass();
doTheInjection(u, 23);
System.out.println(u.getTheValue());
} // main ()
} // class
Run output:
------- fields : --------
-> private int MyClass.theValue
found annotation: #Inject()
injecting !
23
It's also worth noting, that some frameworks utilize bytecode engineering via a custom classloader to achieve the same result without the cost of Reflection (reflection can be pretty expensive at times)

Categories

Resources