开发者

What's the difference between "annotation" in the Java sense and in the iPhone SDK sense?

what is annotation class. what is the use of it in java/android.

In iphone Annotation is used to drop a pin on the map..

java has java.lang.Annotation package... what is the use of it? can i have a examp开发者_如何学Goles, tutorials,sample codes, etc?


The two concepts are unrelated:

  • In the iPhone SDK, an annotation is a sort of note that you can put on a map.
  • In Java (and the Android SDK), annotations are a feature of the Java language used to add specific kinds of metadata to classes.

In the Java world, annotations are compile-time tags which are attached to a piece of code. They add metadata to a snippet of code which tools or third parties (or even your own code) can then use later. But they usually don't affect the way that code runs; that is, if you deleted the annotation, that snippet of code typically shouldn't behave any differently.

A simple example is marking a piece of code with a copyright notice. Here's an annotation that we might use for this:

public @interface Copyright {
    String value();
}

And here's how we'd attach that metadata to code:

@Copyright(value = "2010, United States National Security Administration")
public class QuantumCryptographyDecoder { ... }

If there's only one annotation property named value you can omit the value = specifier as a shortcut:

@Copyright("2010, United States National Security Administration")
public class QuantumCryptographyDecoder { ... }

Otherwise you have to specify it:

@Created(year = 2010)
public class ShinyNewClass { ... }

If we removed the @Copyright annotation, the QuantumCryptographyDecoder would still work the same as it did before. There just wouldn't be any Copyright metadata attached to it. But a third-party tool which did some kind of validation (for instance, requiring that all classes whose names included "Quantum" have a @Copyright notice attached) could alert you to the missing @Copyright or take some other useful action.


Annotaions in Java are really quite powerfull concept. Since annotaion can be introspected with the reflectioon API it comes very handy in doing different jobs. I think the good and simple example is a JAXB API. It allows you to write/read XML files just working with POJOs. Not need to manually marshall/unmarshal XML tree. All you need just to "mark" interested variables that you want to be included in xml with annotations. So it said that this variables holding metadata allowing JAXB API to find out what variables you're interested in and write/read their values to/from XML file.

Don't be disillusioned that annotations just play some "decoration" role like holding author or version info or so. They are much more powerfull...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜