Determine whether field is annotated with a given annotations - java

I don't know if you managed to figure out what i am trying to do just from the title so I'll try to explain with example
Lets suppose I have created my own annotation #VerifySomething
And I have created test class for that annotation to make sure it works.
Now lets suppose that I have class SomeClass with field something anoted with annotation #VerifySomething
class SomeClass {
#VerifySomething
String something;
}
So far so good, but now I want to create test class for my SomeClass however I don't see any point in verifying all the test cases of something as I have already checked that #VerifySomething works as it should in class which tests that annotation, however I need to make sure that field something actually has #VerifySomething annotation without copy pasting all these test cases.
So my question is, is there a way to check if some field has one or more required annotation without writing test cases I have already written in annotation test class to make sure it works as it should.

You can use getAnnotation to determine if there is a specific Annotation on the field, which takes the annotation class as a parameter:
field.getAnnotation( SomeAnnotation.class );
Here is a method you can use to verify that a class has a field annotated by given annotation:
import java.lang.reflect.Field;
import javax.validation.constraints.NotNull;
import org.junit.Test;
import org.springframework.util.Assert;
public class TestHasAnnotatedField {
#Test
public void testHasFieldsWithAnnotation() throws SecurityException, NoSuchFieldException {
Class<?>[] classesToVerify = new Class[] {MyClass1.class, MyClass2.class};
for (Class<?> clazz : classesToVerify) {
Field field = clazz.getDeclaredField("something");
Assert.notNull(field.getAnnotation(NotNull.class));
}
}
static class MyClass1 { #NotNull String something; }
static class MyClass2 { #NotNull String something; }
}

I am not sure I am following, but in case you want to verify whether a class and or its properties have a given Bean Validation constraint, you can use the meta data api. The entry point is Validator#getConstraintsForClass(SomeClass.class). You get a BeanDescriptor. From there you can do _beanDescriptor#getConstraintsForProperty("something") which gives you a PropertyDescriptor. Via propertyDescriptor#getConstraintDescriptors() you get then a set of ConstraintDescriptors which you can iterate to verify that a given constraint annotation was used.
Note, this is a Bean Validation specific solution compared to generic reflection as in the answer above, but it depends what you are really after. To be honest I don't quite understand your use case yet.

Related

haven't provide instance field declaration so I tried to construct the instance.However the constructor or the initialization block threw an exception

class Example extends Parent{
public Example() {
super(Example.class)
}
whenever I am trying the
public class Test{
#InjectMock Example example
#BeforeMethod
#BeforeTest
public void setUp(){
MockitoAnnotations.initMocks(this)
}
}
It is giving the above error mentioned.
Any help is appreciated.
there are a pair of things in your code which not used correctly. I think there is a bit of confusion and is not clear enough what you what to do. I'll try to explain e give you something to read.
#Injectmocks annotation in Test class
The #Injectmocks annotation is used to create a real instance of a class in which you want to inject #Mock objects.
Take a look here for some examples:
https://howtodoinjava.com/mockito/mockito-mock-injectmocks/ ,
https://www.baeldung.com/mockito-annotations
The annotation is an instance field annotation. This means that you cannot use that as you are doing on a method declaration, but you need to use that instead on a field into the test class.
Let's suppose you want to test a method in a class, then you will use this annotation to create an instance of that class which contains the method to be tested. Roughly speaking with analogies, injectmock is like the Spring #Autowire annotation, although not the same.
I've noticed now that probably this is what you where trying to do (the puplished code of the test class has not been highlighetd correctly). You should put new line after #InjectMock Example example. In any case, I think there is a mistake in how you use the super keyword.
Call to super constructor in Example constructor.
I don't know what is the constructor in Parent class and how is done, but the rule is you pass arguments of the Parent construtor in super keyword. So for exampe, if this is your parent constructor:
public Parent(String name){
this.name = name}
then you need to do this in Example:
public Example(String name, String code) {
this.code = code;
super(name);
}
You are passing a .class in super(), not a field.
I would like to give you more help. I suggest you to post your code more clearly and with complete classes.

How to proceed to test a function that receives a "Class" parameter using jMockIt?

I'm developing a function that uses reflection on a Class<?> object that is passed as parameter and returns a POJO with some fields populated, something like this:
public MyPojo functionDeveloper(Class<?> targetClass) { /*...*/ }
This function works fine and does what it needs to do, so no problems on this side.
Now, I need to create a unit test for this function, but I can't really figure out how to proceed here: We are supposed to mock as much as we can (which basically rules out creating a dummy parameter), with some random parameter from a generic class I would go like this:
#Tested
TestedClass testedClassInstance;
#Mocked
private MyGenericClass myGenericClass;
#Mocked
private Field[] fields;
#Test
public void testFunction() {
new Expectations(testedClassInstance) {
myGenericClass.getDeclaredFields();
result = fields;
}
/* assertions here*/
}
...and my intention with the Class<?> parameter was the same: being able to tell "when the code says "targetClass.getDeclaredFields()", then return the mocked object "field" I declared before, but jMockIt is complaining about not being able to mock the Class<?> object.
So, how do I proceed here? I get that java.lang.Class is "special" and all that, and there's probably something I'm missing from how jMockIt works. Any idea?
When you use Mocked on a class, you holds a mocked instance automatically created by jmockit lib.
So, try myGenericClass.getClass().getDeclaredFields()
More details : https://jmockit.github.io/tutorial/Mocking.html#mocked
You have a really simple case of a function. Functions are incredibly easy to test and rarely need mocks. They receive some input and return some output. What you need to do, is to test that some input produced some output.
#Tested
TestedClass testedClassInstance;
#Test
public void egReturnsAllFieldsOfTheProvidedClass() {
MyPojo result = testedClassInstance.functionDeveloper(MyGenericClass.class)
/* assertions here*/
}

How to acces JavaFX fields via Annotation?

What I'm trying to do:
I have a Java program in which I use JavaFX. I created a fxml file in which I created JavaFx controllers, which I then declared in the AddEmployeeOrderController class. I would like to transfer these created controller fields to a POJO. Since I think it is very time-consuming and leads to a lot of careless mistakes, I wanted to automate this process more. My idea was to make an annotation for each declared JavaFX controller field so that, for example, all annotated fields are gonna be retrieved automatically at for example a push of a button in another method. So you can understand it that way instead of writing everything by hand yourself, e.g.:
EmployeeDto employeeDto = new EmployeeDto(textfield.getText(), textfield2.getText()..);
I first formed the AddEmployeeOrderController and declared some JavaFX field and added an annotation. Again in the AddEmployeeOrderController class I tried to access the annotated field.
Then, logically, I would have to cast to cast the java.lang.reflect.Field to a JavaFX TextField, but that is obviously not possible. It throws only IllegalArgumentException errors, and of course because you can't cast a java.lang.reflect.Field to a JavaFX TextField.
Is there a way in which my idea can be achieved with the help of annotation, or am I forced to write everything by hand and generate so-called boilerplate code.
public class AddEmployeeOrderController implements Initializale {
#FXML
#MyAnno
public TextField orderDateFromTextField;
public void atPushButton() {
for (Field field : AddEmployeeOrderController.class.getDeclaredFields()) {
if (field.isAnnotationPresent(MyAnno.class)) {
if (((Field) object).getType().getCanonicalName()
.contains("TextField")) {
TextField textField = (TextField) field.get(this);
textField.getText();
}
}
}
}
}
#Retention(RetentionPolicy.RUNTIME)
public #interface MyAnno {
}
You have not provided sufficient (relevant) code to understand what you are actually doing. However, we can deduce the following:
The Field class you are using is java.lang.reflect.Field.
According to the javadoc, the Field.get(Object) should be called with a reference to an instance ... or null. If an instance is provided, then it needs to be an instance the class that declares the field, or a subclass of that class.
If Field.get is called with a parameter that is NOT of the required class, IllegalArgumentException is thrown.
So ... if what you have told us and shown us is correct ... this is not the correct object to be passing to Field.get on that Field object.
You are saying that the field reflection code you are showing us is in the AddEmployeeController class. That means that this would be a AddEmployeeController instance. But the Field instances you are iterating are for the fields declared by the class AddEmployeeOrderController. So, you should be calling get with a (non-null) value that refers to an AddEmployeeOrderController instance. (Or maybe you should be iterating the declared fields of AddEmployeeController. Without more context it is difficult to say what the correct fix is.)
If we strip away all of the dynamic / reflective stuff, what your code is doing is analogous to this non-reflective code:
public class AddEmployeeOrderController {
public TextField someField;
}
public class AddEmployeeController {
public void someMethod() {
TextField t = (TextField)(this.someField);
}
}
It won't compile because AddEmployeeController doesn't have a field called someField.
What you actually need to do is the analog of this:
public class AddEmployeeController {
public void someMethod(AddEmployeeOrderController aeoc) {
TextField t = (TextField)(aeoc.someField);
}
}
Just to clarify, the problem is not coming from the typecast in
(TextField) field.get(this);
If the typecast was failing, then the exception would be a ClassCastException. The exception you are seeing comes from the get call!
And the problem is not due to annotations.
FOLLOW-UP
I have taken your (attempted) MRE, factored out the JavaFX stuff, and turned it into working code. My version shows how to extract a field value reflectively by matching the field's type and an annotation.
package test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
#Retention(RetentionPolicy.RUNTIME)
public #interface MyAnno {
}
// End of MyAnno
package test;
import java.lang.reflect.Field;
public class MyTest {
#MyAnno
public String someField = "Hi Mom";
public void doIt() throws Exception {
for (Field field : this.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(MyAnno.class)) {
if (field.getType().getCanonicalName().equals("java.lang.String")) {
String value = (String) field.get(this);
System.out.println(value);
}
}
}
}
public static void main(String[] args) throws Exception {
new MyTest().doIt();
}
}
Note that this is REAL code. It compiles, runs and ... works. Try it. If you change String to (say) TextField, you can adapt it to your problem. (The actual type of the field is almost entirely irrelevant to the core problem. As you can see.)
(One thing that could be improved and simplified is that the type test should use Class.equals rather than testing the name of the class. It is cleaner and more reliable.)
One of your concerns was (I think) that you would need a lot of boilerplate code to make this work for your problem. I don't think that is the case:
If I declare an abstract superclass for MyTest and put the implementation of doIt() there ... it should just work. Notice that doIt() uses this.getClass() to get the current object's class.
It would also work if doIt() was in an unrelated class, provided that the method had an argument for passing the target Object.
It would even be possible to parameterize this on the type of the field. Or look for fields that are subtypes of a given type. And so on. (Hint: you would need to pass the type as a Class object.)
I said "(attempted) MRE" for a reason. In fact, your code doesn't compile. Indeed, you have a variable (object) which is not declared, and whose intended type and purpose is hard to fathom. I have assumed that it was a mistake, and guessed that your intention was to use field there. But I should not have to guess!
A real MRE needs to be complete and compilable (unless your problem is how to get it to compile). Ideally it should also be runnable, and running the MRE should reproduce the problem you are asking about.
The point is that we (people trying to help you) need to be sure that we understand what your problem is. That is the purpose of the MRE.

Get outer class by member annotation

I have a class with custom annotation for one of class field:
public class Test {
#CustomAnnotation
private String name;
...
}
I just want to know if it possible to get Class<Test> by this annotation? Can't find any suitable api..
public Class<?> getOuterClass(CustomAnnotation annotation) {
...
}
#CustomAnnotation is declared as #Retention(RetentionPolicy.RUNTIME)
No, annotation does not store any data about where it was declared.
Also annotation can work just like any normal interface, so someone can implement annotation in class an make instances of it that were never used as annotations.
You need either include that information yourself, by adding parameter to annotation and then using it #CustomAnn(Test.class) or when reading annotations just remember and include that information yourself in some other object.

Custom Annotation not found while unit testing

say i've an Annotation like that:
#Retention(RetentionPolicy.RUNTIME)
public #interface AutoConvert {
boolean enabled() default true;
}
and class annotated with it:
#AutoConvert
public class ExampleCommandToExample extends BaseConverter{}
On the superclass i'am doing the following:
public void convert(){
Annotation annotation = (AutoConvert) this.getClass().getAnnotation(AutoConvert.class);
}
Everything works fine on runtime! Annotation is getting found and properly set!
But! While unit testing the convert method with JUnit:
this.getClass().getAnnotation(AutoConvert.class)
always returns null.
The test looks like this:
#Test
public void convertTest(){
//when
exampleCommandToExample.convert();
}
Are custom annotations not being found by reflection while running unit tests?
Does anyone has an answer for me?
I would really really appreciate it.
Thank you in advance.
EDIT:
Alright it seems to be grounded in the kind of intatiation...
I do the following:
exampleCommandToExample = new ExampleCommandToExample() {
#Override
public Type overideSomeMethod() {
return type;
}
};
May it be possible that an instance looses all it's annotations
if I override some methods on instantiation?
Since exampleCommandToExample ref represents an instance of an anonymous class, the call this.getClass().getAnnotation(AutoConvert.class) collects the annotations at its level and all inherited ones.
However, #AutoConvert in this example of anonymous implementation is not inherited, that is why getAnnotation returns null, which corresponds exactly to the behavior declared in Java API:
Returns this element's annotation for the specified type if such an annotation is present, else null.
To solve the issue, simply add
import java.lang.annotation.Inherited;
#Retention(RetentionPolicy.RUNTIME)
#Inherited
public #interface AutoConvert { /* no changes */ }
#Inherited will make the annotation visible for the anonymous implementation.

Categories

Resources