Java Annotations Values Provided in Dynamic Manner

Java Annotations values provided in dynamic manner

There is no way to dynamically generate a string used in an annotation. The compiler evaluates annotation metadata for RetentionPolicy.RUNTIME annotations at compile time, but GENERIC_GENERATED_NAME isn't known until runtime. And you can't use generated values for annotations that are RetentionPolicy.SOURCE because they are discarded after compile time, so those generated values would never be known.

Passing dynamic parameters to an annotation?

No. The annotation processor (the annotation-based framework you're using) needs to implement an approach to handling placeholders.


As an example, a similar technique is implemented in Spring

@Value("#{systemProperties.dbName}")

Here Spring implements an approach to parsing that particular syntax, which in this case translates to something similar to System.getProperty("dbName");

I want to provide dynamic values to the paramaters of Citrus annotation(@CitrusXmlTest)

What you are trying to do is against Java annotation specification and is not possible due to these language limitations. Not sure what you are trying to achieve here.

In case you need to load test cases in a dynamic way you can use packageScan option in @CitrusXmlTest annotation:

@CitrusXmlTest(packageScan = "com.something.foo")
public void citrusPackageScanIT() {}

This will load and execute all XML test case definitions in package com.something.foo. The XML test definitions are free to use different test names then.

If you want to pass some dynamic data to your test case you should use a TestNG data provider (example given here: https://github.com/christophd/citrus-samples/tree/master/sample-dataprovider).

How-to dynamically fill a annotation

You can't achieve this with annotations, but a solution to your specific problem is to implement a custom NamingStrategy:

public class NamingStrategyWrapper implements NamingStrategy {
private NamingStrategy target;

public NamingStrategyWrapper(NamingStrategy target) {
this.target = target;
}

public String columnName(String arg0) {
if ("columnameA".equals(arg0)) return getColumnName();
else return target.columnName(arg0);
}

...
}

-

AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.setNamingStrategy(new NamingStrategyWrapper(cfg.getNamingStrategy()));
factory = cfg.configure().buildSessionFactory();


Related Topics



Leave a reply



Submit