Overwrite Annotations with Reflection? - java

I'm using Oval to do validations, so we have code that looks like this:
#NotNull(errorCode = "NumberInvalid")
#NotNegative(errorCode = "NumberInvalid")
#Range(errorCode = "NumberInvalid", min=1, max=10)
protected Integer dollarAmount;
I want to be able to update the range dynamically if needed, say if we have a config file that changes every month or so, I want to be able to reflect those changes in the validation.
Is there a way I can do this with reflection so that I don't have to subclass every annotation in Oval?

As far as I'm aware this is not possible. Assuming your annotation retention is set to RUNTIME (which it would have to be for the validation to work) then what you will effectively have is a proxy class that implements the annotation interface, you won't be able to amend the values through reflection.

Though annotations looks cleaner with static codes :) but ...there is a way.. Did you tried using reflection ? can you post the approach . You can have a look at this

The purpose of reflection is to access class members (including setting fields), but it does not cover adding new members or modifying existing declarations. What you want is more similar to bytecode editing or code refactoring.

Related

GWT interface like Constants

In my application I need to use dynamic localization, so I cannot use Constants interface. I did use Constants for a while, but now I need texts to be changed without compiling so I had to find some other way.
So I am using Dictionary now. The thing is, when I now want to use text in UiBinder, I can only use methods without arguments. So I created class "StringIdentifiers" where I have the same methods I previously had in MyConstants, but I have to specify a body here for every method to return the specified String.
So for example I have:
Dictionary locale = Dictionary.getDictionary("myJsObjectWithStrings");
//and then the methods for returning the actual strings from the JS object
String loading(){
return locale.get("loading");
}
I would like the method to only be
String loading();
since the rest is always the same with the name of the method appearing as String parameter in the get() method. Possibly even returning some default value when the String is missing in the JS object. But I do not know how to do that. I checked the Constants interface, but I do not really understand the code there. Can someone please give me an example how to implement such a thing?
There is no standard feature in GWT to do this, but you could create one yourself. It's a bit of a stretch, but it should work by using the GWT generator mechanisch. In global terms it should work as follows:
Create an interface (say MyMessages) with a the method names.
To use it use MyMessages message = GWT.create(MyMessages.class). Where you need the text message.loading().
Create a generator that generates an class implementing the interface. This class will created at compile time and should contain the implementation of the interface methods, like in your example.
Add a generate-with tag in your gwt.xml file to make it work.
This is a bit of a brief explanation, but I hope it helps. For more background information about generators see: What is the use GWT generator? or http://blog.arcbees.com/2015/05/26/how-to-write-gwt-generators-efficiently/
You could even reuse some of GWT's annotation's of the i18n to add for example default texts. Add the annotation to your interface and in the generator scan the annotation and use it in the code generation part.

Can I somehow create 1 annotation to replace another with default values?

I fear title is bad, but could not formulate it better. So, I have this code:
#javax.interceptor.Interceptors({EjbSecurityServerInterceptor.class,PermissionInterceptor.class})
Is there a way to create annotation like #SecuredAsHell, that will be an equivalent to aforementioned annotation? Smth like macros, I suppose.
Thanks
No. Sorry, but the fact is that whatever reflection that is used to locate annotations of type javax.interceptor.Interceptors will only locate annotations of that type. There is not way to indicate that another annotation is somehow equivalent.

Jackson JSON Prefixing

I'm currently using RestEasy(2.3.6) with Jackson(1.9.9) and needing to prefix my JSON arrays with '{} &&' in order to prevent JSON hijacking.
I'm new to Jackson and am having a really hard time understanding where to insert anything like this. I'm not even sure where to insert something like this to make it happen all the time, and I would like to take it one step further and be able to specify to only prefix return values that contain JSON arrays and not regular objects.
I imagine there is a class somewhere I need to subclass and override a method, and then register that class somehow. Has anyone ever done anything like this?
Jukka, the question you linked to led me to a solution. I extended JacksonJsonProvider, and overrode the writeTo() method. There are a few conditions in there and I was able to add jg.writeRaw("{}&&"); before each place it writes the value. Also, since I'm using Spring, I had to annotate my class with #Component in order for it to be found.
Also another gotcha with creating your own JsonProvider subclass is your rest methods must have #Produces('application/json') (you should always be explicit with these anyway) or else the default JsonProvider will be used.

Is it possible to parametrize Java Aspect

Is it possible to parametrize an Aspect? Right now I have an #Integration Aspect and my pointcuts are like:
#AfterReturning(pointcut = "#annotation(Integration)",returning = "result")
So, wherever it finds #Integration, it will call this method. Can I implement something like this:
#Integration("new") or #Integration("deleted"),
to avoid to create new annotation for every case?
Also, if this is possible, how to access this provided value ("new" or "deleted").
Thanks in advance :)
Yes it's possible
Here is description of how to add a value to your annotation
Here is the article full of examples of annotation processing with AspectJ; e.g. Listing 8 shows how to access your annotation value inside of aspect

How to observe / trace class member access in Java / Scala?

I'm developing a Scala extension to an existing Java ORM (Ebean). The goal of this project is to add as much type safety as possible to the ORM.
Instead of
Ebean.find(Product.class).fetch("name", "unit").findList()
I would finally like to be able to write something like
(objects of entity[Product] with attributes name and unit) getIt
(note that this is just a very first DSL approach).
The ORM model is already defined as
#Entity
public class {
public String name;
public String unit;
}
In order to achieve type safety at compile time for the attributes in the query, I would need to access them on e.g. a dummy object like (new Product()).name.
I think this is the best way to ensure that only such model members are used that exists on that class, but, at runtime, I need a way to recognize that this variable was accessed. Otherwise I would just call that member name and wouldn't know about this in my query.
Does anybody know a way how to achieve this? Is there a possibility to trace when a variable is accessed and to give that information, at runtime, to any other object?
I already thought about hooking into getters and setters instead of using public members in the model classes, but this would either make the query or the model very ugly. Another problem is that any additional specific methods would have to be added manually for each model.
I would be happy if anyone could suggest possible solutions. Thanks!
If you are willing to define the fields of your model objects as something like the Record Fields, what Emil suggested could work, but if you're building your solution on top of a Java ORM using custom types might be an issue. If you need to track field access I think your best bet will be runtime bytecode instrumentation using a library like CGLib or Javassist. You can pass an instrumented "dummy" object into the body of your function, then track which field was accessed in a thread local. That's how it's done in Squeryl.
You could take a gander at how the Lift folks have implemented Mapper and Records. It allows for type safe queries using companion objects (as well as using raw sql). It does require inheriting traits into your model and the fields are specified as objects and not regular vals. Might be helpfull though. You can find the source for the persistance stuff here.

Categories