How does Lombok.val actually work? - java

Lombok.val allows you to
use val as the type of a local variable declaration instead of
actually writing the type. When you do this, the type will be inferred from the initializer expression. The local variable will also be made final.
So instead of
final ArrayList<String> example = new ArrayList<String>();
You can write
val example = new ArrayList<String>();
I've tried to do some research into how this actually works but there doesn't seem to be a huge amount of information. Looking at the github page, I can see that val is an annotation type. The annotation type is then used, rather than an actual annotation.
I wasn't even aware you could even use annotation types in this manner but upon testing it the following code is indeed valid. However, I'm still not sure why you would ever want to use the type in this way.
public class Main
{
public #interface Foo { }
public static void main(String... args)
{
Foo bar;
System.out.println("End");
}
}
How does Lombok process these usages if they are not annotations, but annotation types? To my (obviously incorrect) understanding, the syntax should look more like:
#Val foo = new ArrayList<String>();
(I'm aware constraints of annotations mean the above is not valid syntax)

In order for Lombok to work, the source code needs to parse without errors. That's why, as you already mentioned, #val foo = new ArrayList<String>(); wouldn't work.
Although Lombok uses annotations, and an annotation processor, the annotation processor is only used as a means to get involved by the compiler.
Lombok does not have a registered processor for #val. Instead, it processes all java files, visits the whole AST and replaces val by the type of the initialization expression of the local variables.
For the actual replacement, for Eclipse/ecj see this class and this one. For javac, see this class.
Disclosure: I am a Lombok developer.

Related

Is there a way to access default values in an annotation statically?

Suppose you have some annotation Annot:
#Retention(/*your retention policy*/)
#Target(/*targeted element type*/)
public #interface Annot {
String value() default "Hello World!";
}
And in some related code, say, an annotation processor, you need the default value of the value() Annotation field without having access to a class that is annotated with #Annot. Of course you could simply do
public static final String ANNOT_VALUE_DEFAULT = "Hello World!";
in your processor class, then change the following in #Annot:
String value() default Processor.ANNOT_VALUE_DEFAULT;
(Processor being the class name of your annotation processor). While this works fine with Strings, the change in #Annot fails when your value() type is an enum. It might fail for other values, too, but enum is part of my use case, therefore if this doesn't work, it doesn't matter if other types will work.
Now, of course, the simplest way to resolve this is to simply have the default value specified in #Annot and Processor, separately. But every programmer knows that duplicated constants are not a good idea in general. You might want to automatically reflect changes in one part (e.g. #Annot) in the other parts (e.g. Processor). For this to work, you'd have to be able to do this:
var defaultVal = Annot.value(); // statically (without an instance annotated with #Annot) access default value
So, is this static access in any way possible?
Partial solution
It is not urgent for me to find a solution right now as I already found a semi-convenient workaround (see my answer). Still, because the workaround is a bit "hacky", I want to know if there is a more elegant way to do this.
Workaround
If it turns out that there is no satisfying solution to this, but you, the reader, really need a solution, take a look at this workaround:
So, the problem is that you want to access the default value without being supplied with a class that is annotated with #Annot. Well, who says that you don't have access to such a class? Just add this (preferably package-private) class to your source code:
#Annot
class DefaultAnnotValues {
private static final Annot ANNOT = DefaultAnnotValue.class.getAnnotation(Annot.class);
static SomeEnum value = ANNOT.value();
// add all other enum fields with default values here
private DefaultAnnotValues() {
}
}
Now you can access all default values of your annotation, and when you change a default value in the annotation definition, it will be automatically reflected to wherever you use those defaults.

How can we access methods generated by ByteBuddy in compilation time?

I wrote this example:
E someCreateMethod(Class<E> clazz) {
Class<? extends E> dynamicType = new ByteBuddy()
.subclass(clazz)
.name("NewEntity")
.method(named("getNumber"))
.intercept(FixedValue.value(100))
.defineField("stringVal", String.class, Visibility.PRIVATE)
.defineMethod("getStringVal", String.class, Visibility.PUBLIC)
.intercept(FieldAccessor.ofBeanProperty())
.make()
.load(clazz.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
return dynamicType.newInstance();
}
And I would like to use it to get the redefined number atributte:
Integer num = someCreateMethod(EntityExample.class).getNumber(); //(1)
Or to get the newly defined stringVal attribute:
String sVal = someCreateMethod(EntityExample.class).getStringVal(); //(2)
My problem is that (1) works pretty fine, while (2) doesn't. I get the following error:
Error:(40, 67) java: cannot find symbol
symbol: method getStringVal()
Also, is it possible to do something like this with a dynamic generated class:
NewEntity newEntity = someCreateMethod(EntityExample.class);
Integer num = newEntity.getNumber();
String sVal = newEntity.getStringVal();
?
EDIT: I appreciate your help, this example was my first attempt on using ByteBuddy library. I figured that defineMethod actually defines an implementation of an interface method, not just add a random method to the class. So I decided to explain here what exactly I'm trying to accomplish.
For every Date attribute in a class E, I want to add two more fields (and theirs respectives getters and setters), let's say (atribute name)InitialDate and (atribute name)FinalDate, so that I can use intervals functinality for every date in E.
I was wondering if I could use code-generation to add those methods without having to create subclasses for every E.
PS: E can't be changed, it belongs to a legacy module.
PS2: I don't know how many date attributes there would be in each entity E, but the new attibutes and methods would be created using conventions (for example __FisrtDay , __LastDay), as shown below:
NewA a = eb.create(A.class);
a.getDeadLine(); //inherited
a.getDeadLineFirstDay(); //added
a.getDeadLineLastDay(); //added
NewA b = eb.create(B.class);
b.getBirthday(); //inherited
b.getBirthdayFirstDay(); //added
b.getBirthdayLastDay(); //added
b.getAnniversary(); //inherited
b.getAnniversaryFirstDay(); //added
b.getAnniversaryLastDay(); //added
PS3: Is what I'm trying to accomplish even possible with ByteBuddy or at all? Is there another way?
PS4: Should my EDIT have been a new question?
You need E to be a superclass/ or interface which includes the methods you are trying to call -- you will not be able to resolve subtyped methods which do not exist on E.
This is not a ByteBuddy issue, this is an issue of your class design -- you should design & group the functionality you intend to generate into abstractable parts, so it can be exposed via types which are meaningful at compile time.
For example, we could use a supertype 'ValueProvider' and then use ByteBuddy to define an IntConstantProvider.
public interface ValueProvider<T> {
public T getValue();
}
Class<? extends ValueProvider<Integer>> dynamicType = new ByteBuddy()
.subclass(clazz)
.name("ConstantIntProvider")
.method(named("getValue"))
.intercept(FixedValue.value(100))
// etc.
Your prototype had 3 separate functionalities (if we consider unreference private fields to be the stub of some intended behavior) with no obvious abstraction to encompass them. This could be better designed as 3 simple atomic behaviors, for which the abstractions would be obvious.
You could use reflection to find arbitrary methods on a arbitrary dynamically-defined class, but this is not really meaningful from a coding or design POV (how does your code know which methods to call? if it does know, why not use a type to express that?) nor is it very performant.
FOLLOWING EDIT TO QUESTION -- Java Bean properties work by reflection, so the example of finding "related properties" (such as First/ Last Date) from known properties is not unreasonable.
However it could be considered to use a DateInterval( FirstDate, LastDate) class so that only one supplementary property is needed per- base property.
As Thomas points out, Byte Buddy generates classes at runtime such that your compiler cannot validate their existance during compile time.
What you can do is to apply your code generation at build time. If your EntityExample.class exists in a specific module, you can enhance this module with the Byte Buddy Maven or Gradle plugin and then, after enhancement, allow your compiler to validate their existance.
What you can also do would be to define interfaces like
interface StringVal {
String getStringVal();
}
which you can ask Byte Buddy to implement in your subclass which allows your compiler to validate the method's existance if you represent your subclass as this interface.
Other than that, your compiler is doing exactly what it is supposed to do: telling you that you are calling a method that does not exist (at that time).

ElementType.LOCAL_VARIABLE annotation type

I`d like to create my own annotations to annotate some local variable. To write the annotation is not the problem, the problem is to get the information of them at the Runtime. I could only get some information from annotated methods or method parameters, but not from local variables. Is there any way to get it?
My own annotation is something like that:
public void m(int a)
#MyOwnAnnotation(some information)
int b = 5;
}
Or, as an alternative, is there any way to get the code of the method, to parse it further and finally get annotation value?
Thanks in advance.
With reflection you can't retrieve a local variable. So you can't retrieve an annotation on a local variable via reflection. I think that this kind of annotation is only used for compiler warnings.
You can look http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html
Local variable annotations are not retained in class files (or at runtime) regardless of the retention policy set on the annotation type. See JLS 9.6.1.2.
If you wan't to retrieve method code, you can use JavaParser (http://javaparser.org/).
As of Java 8, local variable annotations are retained in class files. As noted by Erick Hagstrom, this long-standing bug was fixed by JSR 308, which also added type annotations to the Java language.
However, Java's reflection API has not been updated to give access within method bodies. You will need to parse the classfile yourself. You can use a tool such as ASM. EDIT: I don't recommend JavaParser, because it has not been updated beyond Java 1.5. JavaParser has been updated.
JLS 9.6.1.2 does indeed state that local variable annotations are not retained. However, JSR 308 is working its way through the community process. It should give you the capability you need.
If you want an interim solution, here is an implementation of JSR 308.
At the moment, as mentioned in some other posts, you cannot retrieve a local variable value simply from the annotation alone.
However, I did have a simimlar issue and managed to come up with a solution using fields. Sample code is below:
Interface Class
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface test{
}
PoJo
public class testObject{
#test
private String one;
private String two;
//Getters and Setters
}
Get Object values
public void getFields (Object obj){
Field fields = obj.getClass().getDeclaredFields();
for (Field f : fields){
test fieldAnnotation = f.getAnnotation(test.Class);
if (fieldAnnotation != null){
f.get(obj);
// Do things here based on the values
}
}
}
Main Class
public static void main(String[] args){
//Create object
testObject test = new testObject();
test.setOne("testOne");
test.setTwo("testTwo");
getFields(test);
}
Hopefully this helps in explaining how you can get the fields for an object based on the annotation. You are simply using the annotation to 'mark' the fields you want to retrieve and then reading the value from the object.

Java JUnit array of classes for SuiteClasses syntax

Currently I have the following code to test my class...
#RunWith(Suite.class)
#SuiteClasses( { MyClass.class, MyNewClass } )
public class AllTests {
public static void suite() {
}
}
What I'd like to do would be the following, but it's syntactically incorrect - what would be the correct format?...
Class<?>[] classArray = new Class<?>[] {
MyClass.class, MyNewClass.class
};
#RunWith(Suite.class)
#SuiteClasses( classArray )
public class AllTests {
public static void suite() {
}
}
Unfortunately you can't. Annotations need to take compile-time constants, so you have to use { MyClass.class, MyNewClass.class }.
--- Update ---
The problem seems to stem from Annotations. Annotations require compile time constants, which means you cannot "build an array" of classes in a manner that might have you reassigning the array, or modifying it before the annotated method could access it.
Credit to artbristol for pointing out the obvious. Initially I started down the wrong path, which was to attempt to find out why your array did compile in my 1.7 environment.
Actually, the compile time constant restriction on Annotations makes perfect sense when considering that Annotations are meant to extends java programming via declarative means.
--- Original Post ---
Instead of attempting a wildcard, use
Class<Object>[] classArray = new Class<Object>[] { .... };
It semi-defeats the purpose of generics, since everything extends from Object; but, it will satisfy the "shove anything into it" requirements you need.
By K.Sierra from "SCJP study guide":
"Keep in mind that the wildcards can be used only for reference declarations
(including arguments, variables, return types, and so on). They can't be used as the
type parameter when you create a new typed collection. Think about that—while
a reference can be abstract and polymorphic, the actual object created must be of a
specific type."
List<?> foo = new ArrayList<? extends Animal>();
Problem: you cannot use wildcard notation in the object creation. So the
new ArrayList() will not compile.
EDIT:
#artbristol pointed another problem which is compile-time constant passed to the annotation. Look at the responses in this thread, they might be helpful. One of them suggests ENUM as a workaround.
How to use an array constant in an annotation

Compiletime validation of enum parameters

There is a constructor with three parameters of type enum:
public SomeClass(EnumType1 enum1,EnumType2 enum2, EnumType3 enum3)
{...}
The three parameters of type enum are not allowd to be combined with all possible values:
Example:
EnumType1.VALUE_ONE, EnumType2.VALUE_SIX, EnumType3.VALUE_TWENTY is a valid combination.
But the following combination is not valid:
EnumType1.VALUE_TWO, EnumType2.VALUE_SIX, EnumType3.VALUE_FIFTEEN
Each of the EnumTypes knows with which values it is allowed to be combined:
EnumType1 and the two others implement a isAllowedWith() method to check that as follows:
public enum EnumType1 {
VALUE_ONE,VALUE_TWO,...;
public boolean isAllowedWith(final EnumType2 type) {
switch (this) {
case VALUE_ONE:
return type.equals(Type.VALUE_THREE);
case VALUE_TWO:
return true;
case VALUE_THREE:
return type.equals(Type.VALUE_EIGHT);
...
}
}
I need to run that check at compile time because it is of extreme importance in my project that the combinations are ALWAYS correct at runtime.
I wonder if there is a possibility to run that check with user defined annotations?
Every idea is appreciated :)
The posts above don't bring a solution for compile-time check, here's mine:
Why not use concept of nested Enum.
You would have EnumType1 containing its own values + a nested EnumType2 and this one a nested EnumType3.
You could organize the whole with your useful combination.
You could end up with 3 classes (EnumType1,2 and 3) and each one of each concerned value containing the others with the allowed associated values.
And your call would look like that (with assuming you want EnumType1.VALUE_ONE associated with EnumType2.VALUE_FIFTEEN) :
EnumType1.VALUE_ONE.VALUE_FIFTEEN //second value corresponding to EnumType2
Thus, you could have also: EnumType3.VALUE_SIX.VALUE_ONE (where SIX is known by type3 and ONE by type1).
Your call would be change to something like:
public SomeClass(EnumType1 enumType)
=> sample:
SomeClass(EnumType1.VALUE_ONE.VALUE_SIX.VALUE_TWENTY) //being a valid combination as said
To better clarify it, check at this post: Using nested enum types in Java
So the simplest way to do this is to 1) Define the documentation to explain valid combinations and
2) add the checks in the constructor
If a constructor throws an Exception than that is the responsibility of the invoker. Basically you would do something like this:
public MyClass(enum foo, enum bar, enum baz)
{
if(!validateCombination(foo,bar,baz))
{
throw new IllegalStateException("Contract violated");
}
}
private boolean validateCombination(enum foo, enum bar, enum baz)
{
//validation logic
}
Now this part is absolutely critical. Mark the class a final, it is possible that a partially constructed object can be recovered and abused to break your application. With a class marked as final a malicious program cannot extend the partially constructed object and wreak havoc.
One alternative idea is to write some automated tests to catch this, and hook them into your build process as a compulsory step before packaging/deploying your app.
If you think about what you're trying to catch here, it's code which is legal but wrong. While you could catch that during the compilation phase, this is exactly what tests are meant for.
This would fit your requirement of not being able to build any code with an illegal combination, because the build would still fail. And arguably it would be easier for other developers to understand than writing your own annotation processor...
The only way I know is to work with annotations.
Here is what I do I mean.
Now your constructor accepts 3 parameters:
public SomeClass(EnumType1 enum1,EnumType2 enum2, EnumType3 enum3){}
so you are calling it as following:
SomeClass obj = new SomeClass(EnumTupe1.VALUE1, EnumTupe2.VALUE2, EnumTupe1.VALUE3)
Change the constructor to be private. Create public constructor that accept 1 parameter of any type you want. It may be just a fake parameter.
public SomeClass(Placeholder p)
Now you have to require to call this constructor while each argument is annotated with special annotation. Let's call it TypeAnnotation:
SomeClass obj = new SomeClass(TypeAnnotation(
type1=EnumType1.VALUE1,
type2=EnumTupe2.VALUE2,
type3=EnumTupe1.VALUE3)
p3);
The call is more verbose but this is what we have to pay for compile time validation.
Now, how to define the annotation?
#Documented
#Retention({RetentionPolicy.RUNTIME, RetentionPolicy.SOURCE})
#Target(PARAMETER)
#interface TypeAnnotation {
EnumType1 type1();
EnumType2 type3();
EnumType3 type3();
}
Please pay attention that target is PARAMETER and retention values are RUNTIME and SOURCE.
RUNTIME allows reading this annotation at runtime, while SOURCE allows creating annotation processor that can validate the parameters at runtime.
Now the public constructor will call the 3-parameters private construcor:
public SomeClass(Placeholder p) {
this(readAnnotation(EnumType1.class), readAnnotation(EnumType2.class), readAnnotation(EnumType3.class), )
}
I am not implementing readAnnotation() here: it should be static method that takes stack trace, goes 3 elements back (to caller of the public costructor) and parses annotation TypeAnnotation.
Now is the most interesting part. You have to implement annotation processor.
Take a look here for instructions and here for an example of annotation processor.
You will have to add usage of this annotation processor to your build script and (optionally) to your IDE. In this case you will get real compilation error when your compatibility rules are violated.
I believe that this solution looks too complicated but if you really need this you can do this. It may take a day or so. Good luck.
Well, I am not aware of a compile time check but I do not think it is possible because how can the compiler know which value will be passed to the constructor (In case the value of your enum variable is calculated in runtime (e.g. by an If clause) ?
This can only be validated on runtime by using a validator method as you implemented for the enum types.
Example :
If in your code you have something like this :
EnumType1 enumVal;
if (<some condition>) {
enumVal = EnumType2.VALUE_SIX;
} else {
enumVal = EnumType2.VALUE_ONE;
}
There is no way the compiler can know which of the values will be assigned to enumVal so it won't be able to verify what is passed to the constructor until the if block is evaluated (which can be done only in runtime)

Categories