Bob
Bob

Reputation: 23010

Is there any java annotation for adding extra information to a filed?

Is there any java annotation for adding extra information to the filed of a class?

I need something like the following example to be accessible at run-time by reflections:

public class A
{
   @Description("my field")
   public String name = "";
}

Upvotes: 4

Views: 3647

Answers (1)

Brian
Brian

Reputation: 17319

It's not hard to write something like this yourself. For example:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Description {
    String value() default "";
}

Then to use it:

public class MyClass {

    @Description("my field")
    private String name = "";
}

And to get the value:

Field nameField = MyClass.class.getDeclaredField("name");
Description d = nameField.getAnnotation(Description.class);
System.out.println(d.value()); // Prints "my field"

Key pieces:

  • Note that value is a special attribute. It doesn't require you to specify the name. If you didn't use value, you'd have to do something more like @Description(desc = "my field") and reference the name of it directly.
  • default specifies the default value. It doesn't make much sense here, but it's useful to know. This means you could write @Description without a value specified and this would be legal. Calling value() will return the empty string in this case since that's the default value. If you don't specify a default, then you're required to provide a value.
  • @Target is used to specify what kind of element(s) the annotation can be used on. In this case, we specified only FIELD.
  • @Retention specifies how long it's kept around and whether or not it can be accessed. SOURCE means that it's lost after compiling. This is useful when you only need it for annotation processing. CLASS means that it's stored in the bytecode, but you can't access it through reflection. RUNTIME is the same as CLASS, except you can access it through reflection.

Upvotes: 8

Related Questions