Note that there are some explanatory texts on larger screens.

plurals
  1. POJava annotation to set field to a static instance?
    primarykey
    data
    text
    <p>I've been playing with annotations, and I'm wondering how to go about doing this. What I'd like to do is to be able to have a field declared in a class and annotated such that the field will be initialized with a static instance of the class.</p> <p>Given an annotation like this:</p> <pre><code>@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) //or would this be RetentionPolicy.CLASS? public @interface SetThisField { } </code></pre> <p>Something like this:</p> <pre><code>public class Foo { @SetThisField private Bar bar; } </code></pre> <p>I've played around with using a parser and setting this at runtime, which works but isn't as elegant as I'd like.</p> <p>I can't find any really good examples of RetentionPolicy.CLASS but the documentation seems to indicate that I could somehow make the declaration of "bar" get compiled into this:</p> <pre><code>private Bar bar = Bar.getInstance(); </code></pre> <p>It wouldn't look that way in the source code of course, but it would in the byte code and it would behave like that at runtime.</p> <p>So am I off base here? Is this possible? Or is the parser the way to go with it?</p> <p>UPDATE: This is the guts of the parser I'm using</p> <pre><code>public static void parse(Object instance) throws Exception { Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { //"Property" annotated fields get set to an application.properties value //using the value of the annotation as the key into the properties if (field.isAnnotationPresent(Property.class)) { Property property = field.getAnnotation(Property.class); String value = property.value(); if (!"".equals(value)) { setFieldValue(instance, field, properties.getProperty(value)); } } //"Resource" annotated fields get static instances of the class allocated //based upon the type of the field. if (field.isAnnotationPresent(Resource.class)) { String name = field.getType().getName(); setFieldValue(instance, field, MyApplication.getResources().get(name)); } } } private static void setFieldValue(Object instance, Field field, Object value) throws IllegalAccessException { boolean accessibleState = field.isAccessible(); field.setAccessible(true); field.set(instance, value); field.setAccessible(accessibleState); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload