Pregunta

I was writing code where database my table name has to be changed depending on whether I'm in my dev environment or prod environment. The table name is being defined as an annotation since I'm using Dynomo DB's high level API. So for example is the following code possible and what are the rules that govern its behavior:

static String postfix = "_test"; // (could be set to say _prod, _dev, etc.)

@DynamoDBTable(tableName="sometable" + postfix)
class MyTable {
  ...
  ...

The cluster of questions this leads to is:

  1. When are annotations in Java Bound? Compile time or Run time?
  2. Can the binding be changed midstream execution?

Thanks.

¿Fue útil?

Solución

Annotations in java have to have values which are resolvable at compile time. There cannot be any runtime information in the annotation, as it's part of the class definition itself. If runtime information is needed, it will have to be resolved by whoever is looking for the annotation at runtime.

As for retention, there are 3 forms of retention:

  1. Source- the annotations are used by the compiler (typically for hints and/or source generation). Examples include @Override and @SuppressWarnings, and are discarded after all annotation processors have been given a chance to see them. Nothing is recording in the .class file.

  2. Class - the annotations are saved as part of the .class file itself, and is available to tools which can parse class byte[] data (javassist, etc...), but are not part of the actually java Class object which is loaded.

  3. Runtime - The annotations are available from compile time all the way through to runtime as part of the java Class object.

Otros consejos

It depends on how annotation is defined. "Retention" defines whether it is compile time or runtime.

Using java reflections you could possibly so a setAccessible(true); and set the Annotation at runtime

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top