Get value of a parameter of an annotation in Java
To get value of the @Path
parameter:
String path = Hello.class.getAnnotation(Path.class).value();
Similarly, Once you have hold of Method
getHtml
Method m = Hello.class.getMethod("getHtml", ..);
String mime = m.getAnnotation(Produces.class).value;
It is possible to read the field value with annotations at runtime in java?
Not sure if this is what you're looking for but you can do something like this:
Object getValueForMyAnnotaion(MyClass obj) {
Field[] fieldList = obj.getClass().getDeclaredFields();
for (Field field : fieldList) {
if (field.isAnnotationPresent(MyAnnotation.class)) {
return field.get(obj);
}
}
}
Note that it will return Object
and only for the first member that has the annotation but it can be easily changed to what you need.
easy way to get annotation value of object member in Java
You cannot get the annotations of a field given it's value.
When you are calling your "Util" method, all you are passing it is the value of the field. It won't have enough information to access the annotation.
Here is a way you might do it...
public class SomeClass {
@Digits(fraction = 2, integer = 16)
private BigDecimal amount;
private void setAmount(double d) {
amount = BigDecimal.valueOf(d);
amount.setScale(Util.getFraction(this, "amount"));
}
public static void main(String[] args) {
new SomeClass().setAmount(12.3);
}
}
Notice I'm passing the instance of the object that the field is in and the name of the field to my "Util" method.
It can now get the actual value like this...
public class Util {
public static int getFraction(Object obj, String fieldName) {
try {
Digits annotation = obj.getClass().getDeclaredField(fieldName).getAnnotation(Digits.class);
return annotation.fraction();
} catch (NoSuchFieldException | SecurityException e) {
// BOOM!
throw new IllegalStateException("Something went awfully wrong...", e);
}
}
}
How to read value of java annotation with JDK8 and JDK11?
You should not depend on the toString()
implementation which is normally for debugging/logging only.
See Is it possible to read the value of a annotation in java? for more details on how to read the value of an annotation.
UPDATE:
To do everything via reflection, you can so something like this:
import org.springframework.transaction.annotation.Transactional;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
public class AnnotationTest {
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
Method[] methods = AnnotationTest.class.getMethods();
System.out.println("methods = " + Arrays.toString(methods));
for (Method method : methods) {
System.out.println("method = " + method);
Annotation[] annotations = method.getAnnotations();
System.out.println("annotations = " + Arrays.toString(annotations));
for (Annotation annotation : annotations) {
System.out.println("annotation = " + annotation);
Class<? extends Annotation> annotationClass = annotation.annotationType();
System.out.println("annotationClass = " + annotationClass);
Method[] annotationMethods = annotationClass.getMethods();
System.out.println("annotation methods = " + Arrays.toString(annotationMethods));
for (Method annotationMethod : annotationMethods) {
if (Modifier.isPublic(annotationMethod.getModifiers())) {
String name = annotationMethod.getName();
Object o = annotationMethod.invoke(annotation);
System.out.println(name + ": " + o);
}
}
}
}
}
@Transactional("bla")
public void test() {
}
}
(I used one of Spring's annotations here since that is what I happen to have on my classpath)
UPDATE (with end of solution):
@When(value = "I update text {string} with {string}(\\?)")
public static void main(String[] args) {
Object as[] = { "a", "b" };
Class c = Sof.class;
Method[] methods = c.getMethods();
Method method = null;
for (Method m : methods) {
if (m.getName().equals("main")) {
method = m;
}
}
Annotation stepAnnotation = method.getAnnotation(When.class);
Class<? extends Annotation> annotationClass = stepAnnotation.annotationType();
try {
Method valueMethods = annotationClass.getDeclaredMethod("value");
if (Modifier.isPublic(valueMethods.getModifiers())) {
log.info("---> {} " + String.format(valueMethods.invoke(stepAnnotation).toString().replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), as),
stepAnnotation.annotationType().getSimpleName());
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
e1.printStackTrace();
}
}
Annotation - Read element values with reflection
Yes. You almost have it. Once you reach this part:
iInvokedMethod.getTestMethod().getConstructorOrMethod().getMethod()
.getAnnotation(TestCase.class)
it gives you an object that inherits the TestCase
annotation.
TestCase tc = iInvokedMethod.getTestMethod().getConstructorOrMethod().getMethod()
.getAnnotation(TestCase.class);
String b1 = tc.brand1(); // returns the value "1001" from your example
String b2 = tc.brand2(); // returns the value "1101" from your example
String b3 = tc.brand3(); // returns the value "1201" from your example
edit: to add the other means @SotiriosDelimanolis said.
TestCase tc = iInvokedMethod.getTestMethod().getConstructorOrMethod().getMethod()
.getAnnotation(TestCase.class);
Method fm = TestCase.class.getMethod("brand1"); // or brand2 or a variable
String brand = (String) fm.invoke(tc); // returns the value "1001" from your example
Receive annotation value from annotated field
is it possible to know annotation value inside annotated field
It's not possible.
You may have 2 different classes
class SomeClass {
@MyAnnotation("Annotation")
private MyClass myClass;
public SomeClass(MyClass myClass) {
this.myClass=myClass;
}
}
and
class SomeClassNo Annotation {
private MyClass myClass;
public SomeClassNo(MyClass myClass) {
this.myClass=myClass;
}
}
Then you create an instance of MyClass
MyClass instance = new MyClass();
then 2 classes instancesnew SomeClass(instance)
and new SomeClassNo(instance)
both have reference to the same instance
. So the instance does not know whether the reference field annotated or not.
The only case when it is possible is to pass somehow the container reference to MyClass
.
Related Topics
What's the Best Mock Framework for Java
Differences Between Exception and Error
Creating an Array of Objects in Java
Do Interfaces Inherit from Object Class in Java
How to Delete Stuff Printed to Console by System.Out.Println()
Createprocess Error=206, the Filename or Extension Is Too Long When Running Main() Method
Java 1.6 - Determine Symbolic Links
How to Instantiate an Inner Class with Reflection in Java
Good Way to Encapsulate Integer.Parseint()
Default Constructor VS. Inline Field Initialization
Is There a Common Java Utility to Break a List into Batches
Java.Io.Console Support in Eclipse Ide
What Operations in Java Are Considered Atomic
What's the Syntax for Mod in Java
Java' Is Not Recognized as an Internal or External Command