Forum Controls
Spotlight Features

The Rich Engineering Heritage Behind Dependency Injection

Andrew McVeigh takes us on a tour of the rich heritage behind dependency injection, what it represents, and tells us why its here to stay.

NetBeans 6: Matisse Updates

NetBeans 6 delivers great updates to the Matisse GUI builder. Spend a few minutes with Roman Strobl and get an expert briefing on what's new and what has changed.

Introduction to Groovy Part 3

In this, the third and final installation of Andres' Introduction to Groovy series, you learn about how Groovy handles variable numbers of arguments, named parameters, currying, and more about Groovy operators. Including, some new operators.

Easier Custom Components with Swing Fuse

Swing Fuse (actually just Fuse), is a framework designed to make it easier to create your own custom desktop components. In this article, Daniel Spiewak shows you how to get started and provides sample source code you can download.

Benchmark Analysis: Guice vs Spring

Willam Louth shows how he uses JXInsight Probes to investigate probable performance issues with code bases that he is not familiar with. He also highlights possible pitfalls in creating a benchmark, as well as in the analysis of results.
Replies: 2 - Pages: 1  
Threads: [ Previous | Next ]
  Click to reply to this thread Reply

Annotations: Finding Annotations at Runtime

At 1:45 AM on Feb 21, 2005, R.J. Lorimer wrote:

I'd like to finish this series of tips on annotations by showing how we can write a little program to print our annotations out to the console in a friendly manner. If you recall, we have developed a @Note annotation that was mostly an aide for developers in documentation unfinished parts of their code. Adapting what we learned in the past set of tips...:

Annotations: Utilizing the Standard Annotations
Annotations: Evolving an Annotation - Part 1
Annotations: Evolving an Annotation - Part 2

... we can assume our annotation looks *something* like this:

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
 
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PACKAGE, ElementType.FIELD})
public @interface Note {
    String value();
    Priority priority() default Priority.MEDIUM;
}

As a quick reminder - the summary of this annotation is an annotation named @Note with two properties - value (of type String) and priority (of enumeration type Priority). The annotation is intended for packages, classes, methods, fields, and constructors only (the @Target annotation). The annotation is intended to be part of the documentation of any class it is a part of (the @Documented annotation). Finally, the annotation can be inspected at runtime (the @Retention annotation).

Now, let's say we have a class (or perhaps more realistically, many classes) littered with these annotations. Now what we have been diligent and applied all of these annotations to our classes, how do we interact with them programmatically so we can do cool stuff like print them out in a build script or perhaps even integrate them with an IDE so we can keep a running tab on what needs to be cleaned up (similar to Eclipse's 'Task' view).

The runtime annotation facilities are conveniently integrated with the reflection library APIs (which all incidentally branch off of the Class object). Essentially, all features of the class itself (class, package, fields, methods, constructors, etc) that can be retrieved through reflection may have annotations applied on them. Each of these items now implement the java.lang.reflect.AnnotatedElement interface. What this interface allows is the ability to lookup annotations based on a certain type, get all annotations that are available, and other behaviors of that sort.

Since I strongly believe code speaks 1000 words, here is a class that prints out @Note annotations - I have also attached the source code for the entire example.

import java.lang.reflect.AnnotatedElement;
 
public class AnnotationExample {
 
 public static void main(String[] args) {
  printAnnotationsForClass(MyClass.class);
 }
 
 public static void printAnnotationsForClass(Class classObj) {
  System.out.println("Package Notes:");
  printNote(classObj.getPackage());
 
  System.out.println("\nClass Notes:");
  printNote(classObj);
 
  System.out.println("\nField Notes:");
  printNotes(classObj.getDeclaredFields());
 
  System.out.println("\nConstructor Notes:");
  printNotes(classObj.getDeclaredConstructors());
 
  System.out.println("\nMethod Notes:");
  printNotes(classObj.getDeclaredMethods());
 
 }
 
 public static void printNotes(AnnotatedElement[] elems) {
  for (AnnotatedElement elem : elems) {
   printNote(elem);
  }
 }
 
 public static void printNote(AnnotatedElement elem) {
  if (elem == null || !elem.isAnnotationPresent(Note.class)) {
   return;
  }
  Note annotation = elem.getAnnotation(Note.class);
  String annotationValue = annotation.value();
  Priority annotationPriority = annotation.priority();
  System.out.println(elem.toString() + " - Note: '" + annotationValue
    + "' Priority: " + annotationPriority);
 }
 
 @Note(value = "This class isn't finished", priority = Priority.HIGH)
 public class MyClass {
 
  @Note("This field isn't finished")
  private String fieldA;
 
  @Note("Constructor isn't finished")
  public MyClass() {
 
  }
 
  @Note("methodA isn't finished")
  public void methodA() {
 
  }
 }
 
}

I hope this annotation series have been useful - see you next time!

1 . At 9:18 AM on Feb 21, 2005, R.J. Lorimer wrote:
  Click to reply to this thread Reply

Re: Annotations: Finding Annotations at Runtime

I forgot to attach the source code.

See the attached files.

Cheers,
Best, R.J. Lorimer
2 . At 6:03 PM on Feb 26, 2005, Andy Tripp DeveloperZone Top 100 wrote:
  Click to reply to this thread Reply

Re: Annotations: Finding Annotations at Runtime

Just a reminder to anyone who reads this...
be sure to specify:

@Retention(RetentionPolicy.RUNTIME)

in your annotation. If you don't, the runtime will never
see your annotation, and you'll be quite perplexed for
several hours. Speaking from experience, obviously :(

Andy
Andy Tripp, CTO and Founder Jazillian - Legacy to 'natural' Java.

thread.rss_message