# Thursday, 15 June 2006
« More AtomicInteger Performance | Main | Eclipse Java Compiler »
Custom Attributes as Annotations
I implemented partial and experimental support for applying .NET Custom Attributes in Java code as annotations. The following example now works:


import cli.System.Runtime.InteropServices.DllImportAttribute;

class beep
{
  @DllImportAttribute.Annotation("kernel32")
  private static native int Beep(int dwFreq, int dwDuration);

  public static void main(String[] args)
  {
    for (int i = 1000; i < 3000; i += 200)
      Beep(i, 50);
  }
}

I realise that the name of the annotation type is a bit ugly, but it's consistent with the way delegates are handled and it enables efficient handling of custom attributes at runtime (when compiling code in dynamic mode) and doesn't require access to the ikvmstub generated stub classes.

At the moment only attributes that have a zero arg or single string arg constructor are supported and attribute fields or properties are not exposed.

The Annotation inner interface cannot be used for anything except annotating. If you try to implement it or declare variables or parameters of its type, you will get internal errors in IKVM.Runtime.dll (because there is no corresponding .NET type). I will probably fix this at some point, but for now simply don't use that type except for annotating.

Finally, even though the Annotation annotation type is marked as Retention(RetentionPolicy.RUNTIME), it won't be visible through Java reflection. It's complicated to make this work and the value of it is limited. As an alternative, you can use .NET reflection to access the custom attributes.

Thursday, 15 June 2006 14:31:25 (W. Europe Daylight Time, UTC+02:00)  #    Comments [0]
Name
E-mail
Home page

I apologize for the lameness of this, but the comment spam was driving me nuts. In order to be able to post a comment, you need to answer a simple question. Hopefully this question is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.

Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)

Answer:  
Comment (HTML not allowed)  

Live Comment Preview