During the parsing of certain xml files, I come across a situation that I have to use interface as labels to identify that certain tags belong to certain category, for example, I created a Tag interface to identify that these classes are used to represent xml tags, and ContainableTag to point out that certain tags can be one of the children tags of some tags.
Then I stumble into this page: http://xahlee.org/java-a-day/interface.html (Please look for the "Interface as Labels" session.). It says:
The gist of the problem is that it is
a piece of mathematical irrelevance in
the language. As a labeling mechanism
in a language, for the possible
benefit from the software engineering
perspective, then it should not be
designed as part of the Class
Interface, since the concept of
labeling, and concept of programing
interface, are semantically disparate.
So is interface as labels necessarily a bad practice? As a java programmer, do we have some other alternatives?
Interfaces as markers have largely been replaces by the annotation mechanism in Java 5 or later. They allow you to add arbitrary meta-data. If your interfaces are empty and are only serving to act as class markers, then you should be using annotations instead.
While annotations may provide an alternative for what marker interfaces accomplish, they are only available in Java, and do not integrate well with IDEs: I also use marker interfaces to tag related concepts in my project, and I can then use the type hierarchy browser to find all members (I guess this will be eventually supported by major IDEs for annotations soon).
As for the article you mention, I do not see the point in arguing that if a class syntactically/structurally "fulfills" an interface, that interface may/should be applied automatically to the class ("Any class can declare it [RandomAccess] as a interface..."). That's backwards thinking, in my opinion.
I would argue that the places, where such a marker interface is used in an `instanceof' statement, use inverted logic, but as long as you are stuck within a language without multiple inheritance, aspects and annotations, I see no better way to accomplish this without stepping out of the base language.
Also note that this dead-beat argument about an empty interface always being applicable could also be applied to annotations.
Annotations are not necessarily what you want. Tagging interfaces are a way of working a property of a type into the type itself. For example, if you're about to start writing code looking like this:
#interface ContainableTag{}
#ContainableTag public class Foo {}
// ... elsewhere...
/**
* Adds obj as a child element.
* #throws IllegalArgumentException if obj is not tagged with
* the ContainableTag annotation.
*/
public void addElement(Object obj){
if (!obj.getClass().isAnnotationPresent(ContainableTag.class))
throw new IllegalArgumentException("obj is not a ContainableTag");
// add the containable tag as an element
}
Then consider if you really don't think this looks better:
interface ContainableTag {}
public class Foo implements ContainableTag {}
// ... elsewhere...
public void addElement(ContainableTag ct){
// add the containable tag as an element
}
Sure, the tagging interface does not provide any information about what behavior the type itself provides, but it does allow other types to enforce this non-behavioral property. I certainly would have been spared a lot of annoying bugs if ObjectOutputStream had a writeObject(Serializable) method rather than writeObject(Object).
Edit: I have not insignificant support here.
Related
Why in "java" when you declare a "parameter" of an "annotation" you have to put "pair of parentheses" after the parameter, annotation are anyway "very different" form "interface" syntactically, so why this weird syntax...I know it has something to do with, that annotation are managed using interface behind the scenes or something, but what exactly?
This is what a normal interface declaration would look like:
public interface Example {
String method();
}
Note that when annotations were released, the java feature 'default methods for interfaces' wasn't around yet. The default keyword already existed (and has existed since java 1.0), solely as a thing you can put in a switch block, as the 'case' for 'it didnt match any of the cases'.
This is what an annotation interface definition looks like:
public #interface Example {
String method();
}
or, if defaults are involved:
public #interface Example {
String method() default "";
}
Note how parsing wise there is no difference between these two, other than the '#' symbol. In the 'default' case; yeah that's entirely new, but looking solely at that bit, it's not weird looking. The parentheses are, but not that bit.
The reason it's done this way is to not 'explode' parsing. Since the introduction of module-info in java9, if you want to write a parser for java, you mostly DO need an 'on the fly switching modes' parser; the "language specification" for a module file is so very different.
But that is a big step; the vast majority of parser libraries out there don't deal with this well, they can't switch grammars in the middle of parsing a source file.
Even if I can snap my fingers and break java (which, to be clear, java does not generally do: updating the language so that existing code now no longer compiles or means something else is a big step that is very rarely taken for obvious reasons. It restricts language design, though. That's the cost of being the world's most popular language*)... there are advantages here.
The way annotations work is that, if you at runtime obtain one, it acts like an object that is an instance of the annotation interface:
Example foo = Class.forName("foo.bar.Baz").getAnnotation(Example.class);
System.out.println(foo.method());
Note how it's not foo.method. It's foo.method(). And that has different reasons: fields, in java, are second-rate citizens. You can't put them in lambda method references (ClassName::methodName is valid java; there's no such thing for fields), they don't inherit, you can't put them in interfaces (fields in interfaces are automatically public, final, and static, i.e. constants. They don't decree a requirement to any implementing class, unlike methods in interfaces). That means fields as a general point of principle aren't used in public APIs in java. It'd be weird if in this instance they would be.
So, given that the params act like args-less method calls, it's convenient in that sense that you declare them that way as well in an #interface definition.
*) Give or take a few spots.
I was just looking at the Java Hamcrest code on GitHub, and noticed they employed a strategy that seemed unintuitive and awkward, but it got me wondering if I'm missing something.
I noticed in the HamCrest API that there is an interface Matcher and an abstract class BaseMatcher. The Matcher interface declares this method, with this javadoc:
/**
* This method simply acts a friendly reminder not to implement Matcher directly and
* instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore
* compile errors .
*
* #see Matcher for reasons why.
* #see BaseMatcher
* #deprecated to make
*/
#Deprecated
void _dont_implement_Matcher___instead_extend_BaseMatcher_();
Then in BaseMatcher, this method is implemented as follows:
/**
* #see Matcher#_dont_implement_Matcher___instead_extend_BaseMatcher_()
*/
#Override
#Deprecated
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}
Admittedly, this is both effective and cute (and incredibly awkward). But if the intention is for every class that implements Matcher to also extend BaseMatcher, why use an interface at all? Why not just make Matcher an abstract class in the first place and have all other matchers extend it? Is there some advantage to doing it the way Hamcrest has done it? Or is this a great example of bad practice?
EDIT
Some good answers, but in search of more detail I'm offering a bounty. I think that the issue of backwards / binary compatibility is the best answer. However, I'd like to see the issue of compatibility elaborated on more, ideally with some code examples (preferably in Java). Also, is there a nuance between "backwards" compatibility and "binary" compatibility?
FURTHER EDIT
January 7, 2014 -- pigroxalot provided an answer below, linking to
this comment on Reddit by the authors of HamCrest. I encourage everyone to read it, and if you find it informative, upvote pigroxalot's answer.
EVEN FURTHER EDIT
December 12, 2017 -- pigroxalot's answer was removed somehow, not sure how that happened. It's too bad... that simple link was very informative.
The git log has this entry, from December 2006 (about 9 months after the initial checkin):
Added abstract BaseMatcher class that all Matchers should extend. This allows for future API compatability [sic] as the Matcher interface evolves.
I haven't tried to figure out the details. But maintaining compatibility and continuity as a system evolves is a difficult problem. It does mean that sometimes you end up with a design that you would never, ever, ever have created if you had designed the whole thing from scratch.
But if the intention is for every class that implements Matcher to also extend BaseMatcher, why use an interface at all?
It's not exactly the intent. Abstract base classes and interfaces provide entirely different 'contracts' from an OOP perspective.
An interface is a communication contract. An interface is implemented by a class to signify to the world that it adheres to certain communication standards, and will give a specific type of result in response to a specific call with specific parameters.
An abstract base class is an implementation contract. An abstract base classes is inherited by a class to provide functionality that is required by the base class but left for the implementer to provide.
In this case, both overlap, but this is merely a matter of convenience - the interface is what you need to implement, and the abstract class is there to make implementing the interface easier - there is no requirement whatsoever to use that base class to be able to offer the interface, it's just there to make it less work to do so. You are in no way limited in extending the base class for your own ends, not caring about the interface contract, or in implementing a custom class implementing the same interface.
The given practice is actually rather common in old-school COM/OLE code, and other frameworks facilitating inter-process communications (IPC), where it becomes fundamental to separate implementation from interface - which is exactly what is done here.
I think what happened is that initially a Matcher API was created in the form of an interface.
Then while implementing the interface in various ways a common code base was discovered which was then refactored out into the BaseMatcher class.
So my guess is that the Matcher interface was retained as it is part of the initial API and the descriptive method was then added as a reminder.
Having searched through the code, I found that the interface could easily by done away with as it is ONLY implemented by BaseMatcher and in 2 test units which could easily be changed to use BaseMatcher.
So to answer your question - in this particular case there is no advantage to doing it this way, besides not breaking other peoples implementations of Matcher.
As to bad practice ? In my opinion it is clear and effective - so no I don't think so, just a little odd :-)
Hamcrest provides matching, and matching only. It is a tiny niche market but they appear to be doing it well. Implementations of this Matcher interface are littered across a couple unit testing libraries, take for example Mockito's ArgumentMatcher and across a silly great amount of tiny anonymous copy-paste implementations in unit tests.
They want to be able to extend the Matcher with a new method without breaking all of those existing implementing classes. They would be hell to upgrade. Just imagine suddenly having all your unittest classes showing angry red compile errors. The anger and annoyance would kill hamcrest's niche market in one quick swoop. See http://code.google.com/p/hamcrest/issues/detail?id=83 for a small taste of that. Also, a breaking change in hamcrest would divide all versions of libraries that use Hamcrest into before and after the change and make them mutually exclusive. Again, a hellish scenario. So, to keep some freedom, they need Matcher to be an abstract base class.
But they are also in the mocking business, and interfaces are way easier to mock than base classes. When the Mockito folks unit test Mockito, they should be able to mock the matcher. So they also need that abstract base class to have a Matcher interface.
I think they have seriously considered the options and found this to be the least bad alternative.
There is an interesting discussion about it here. To quote nat_pryce:
Hi. I wrote the original version of Hamcrest, although Joe Walnes
added this wierd method to the base class.
The reason is because of a peculiarity of the Java language. As a
commenter below said, defining Matcher as a base class would make it
easier to extend the library without breaking clients. Adding a method
to an interface stops any implementing classes in client code from
compiling, but new concrete methods can be added to an abstract base
class without breaking subclasses.
However, there are features of Java that only work with interfaces, in
particular java.lang.reflect.Proxy.
Therefore, we defined the Matcher interface so that people could write
dynamic implementations of Matcher. And we provided the base class for
people to extend in their own code so that their code would not break
as we added more methods to the interface.
We have since added the describeMismatch method to the Matcher
interface and client code inherited a default implementation without
breaking. We also provided additional base classes that make it easier
to implement describeMismatch without duplicating logic.
So, this is an example of why you can't blindly follow some generic
"best practice" when it comes to design. You have to understand the
tools you're using and make engineering trade-offs within that
context.
EDIT: separating the interface from the base class also helps one cope
with the fragile base class problem:
If you add methods to an interface that is implemented by an abstract
base class, you may end up with duplicated logic either in the base
class or in subclasses when they are changed to implement the new
method. You cannot change the base class to remove that duplicated
logic if doing so changes the API provided to subclasses, because that
will break all subclasses -- not a big problem if the interface and
implementations are all in the same codebase but bad news if you're a
library author.
If the interface is separate from the abstract base class -- that is,
if you distinguish between users of the type and implementers of the
type -- when you add methods to the interface you can add a default
implementation to the base class that will not break existing
subclasses and introduce a new base class that provides a better
partial implementation for new subclasses. When someone comes to
change existing subclasses to implement the method in a better way,
then can choose to use the new base class to reduce duplicated logic
if it makes sense to do so.
If the interface and base class are the same type (as some have
suggested in this thread), and you then want to introduce multiple
base classes in this way, you're stuck. You can't introduce a new
supertype to act as the interface, because that will break client
code. You can't move the partial implementation down the type
hierarchy into a new abstract base class, because that will break
existing subclasses.
This applies as much to traits as Java-style interfaces and classes or
C++ multiple inheritance.
Java8 now allows new methods to be added to an interface if they contains default implementations.
interface Match<T>
default void newMethod(){ impl... }
this is a great tool that gives us a lot of freedom in interface design and evolution.
However, what if you really really want to add an abstract method that has no default implementation?
I think you should just go ahead and add the method. It'll break some existing codes; and they will have to be fixed. Not really a big deal. It probably beats other workarounds that preserve binary compatibility at the cost of screwing up the whole design.
But if the intention is for every class that implements Matcher to
also extend BaseMatcher, why use an interface at all? Why not just
make Matcher an abstract class in the first place and have all other
matchers extend it?
By separating interface and implementation (abstract class is still an implementation) you comply with Dependency Inversion Principle. Do not confuse with dependency injection, nothing in common. You might notice that, in Hamcrest interface is kept in hamcrest-api package, while abstract class is in hamcrest-core. This provides low coupling, because implementation depends only on interfaces but not on other implementation. A good book on this topic is: Interface Oriented Design: With Patterns.
Is there some advantage to doing it the way Hamcrest has done it? Or
is this a great example of bad practice?
The solution in this example looks ugly. I think comment is enough. Making such stub methods is redundant. I wouldn't follow this approach.
EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.
This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 7 years ago.
How do you name different classes / interfaces you create?
Sometimes I don't have implementation information to add to the implementation name - like interface FileHandler and class SqlFileHandler.
When this happens I usually name the interface in the "normal" name, like Truck and name the actual class TruckClass.
How do you name interfaces and classes in this regard?
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck.
An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc that implements Truck.
When you are using the Interface in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions, could be something like AbstractTruck. Since only the sub-classes will ever see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck or DefaultTruck instead since the abstract is in the definition. But since Abstract classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected goes a long way to crossing this divide.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No, you see List and ArrayList, and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principle as well.
Also, if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even internally adhere to in a consistent manner.
If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have a situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface in most cases.
However, in general for maintainability, testability, mocking, it's best practice to provide interfaces. See this answer for more details.
Also Refer this interesting article by Martin Fowler on this topic of InterfaceImplementationPair
I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).
So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.
in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).
Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.
For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).
I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.
The name of the interface should describe the abstract concept the interface represents. Any implementation class should have some sort of specific traits that can be used to give it a more specific name.
If there is only one implementation class and you can't think of anything that makes it specific (implied by wanting to name it -Impl), then it looks like there is no justification to have an interface at all.
I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:
List - interface for the "conceptual" object
ArrayList - concrete implementation of interface
LinkedList - concrete implementation of interface
AbstractList - abstract "partial" implementation to assist custom implementations
I used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.
The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.
I like interface names that indicate what contract an interface describes, such as "Comparable" or "Serializable". Nouns like "Truck" don't really describe truck-ness -- what are the Abilities of a truck?
Regarding conventions: I have worked on projects where every interface starts with an "I"; while this is somewhat alien to Java conventions, it makes finding interfaces very easy. Apart from that, the "Impl" suffix is a reasonable default name.
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
I use both conventions:
If the interface is a specific instance of a a well known pattern (e.g. Service, DAO), then it may not need an "I" (e.g UserService, AuditService, UserDao) all work fine without the "I", because the post-fix determines the meta pattern.
But, if you have something one-off or two-off (usually for a callback pattern), then it helps to distinguish it from a class (e.g. IAsynchCallbackHandler, IUpdateListener, IComputeDrone). These are special purpose interfaces designed for internal use, occasionally the IInterface calls out attention to the fact that an operand is actually an interface, so at first glance it is immediately clear.
In other cases you can use the I to avoid colliding with other commonly known concrete classes (ISubject, IPrincipal vs Subject or Principal).
TruckClass sounds like it were a class of Truck, I think that recommended solution is to add Impl suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List interface and implementations: ArrayList or LinkedList), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl is the solution.
I'm working with Java 6's annotation processing, i.e. what can be found within javax.annotation.processing (not Java 5's APT).
I wonder what the conceptional difference between the various Element, Type, and Mirror classes is. As I don't really understand this, it's hard to efficiently program an annotation processor. There are various methods that 'convert' between these notions but I'm not really sure what I'm doing when using them.
So, for example, let me have an instance of AnnotationMirror.
When I call getAnnotationType() I get an instance of DeclaredType (which implements TypeMirror for whatever reason).
Then I can call asElement() on this one and obtain an instance of Element.
What has happened?
There is indeed on overlap between these concepts.
Element models the static structure of the program, ie packages, classes, methods and variables. Just think of all you see in the package explorer of Eclipse.
Type models the statically defined type constraints of the program, ie types, generic type parameters, generic type wildcards. Just think of everything that is part of Java's type declarations.
Mirror is an alternative concept to reflection by Gilad Bracha and Dave Ungar initially developed for Self, a prototype-based Smalltalk dialect. The basic idea is to separate queries about the structure of code (and also runtime manipulation of the structure, alas not available in Java) from the domain objects. So to query an object about its methods, instead of calling #getClass you would ask the system for a mirror through which you can see the reflection of the object. Thanks to that separation you can also mirror on classes that are not loaded (as is the case during annotation processing) or even classes in a remote image. For example V8 (Google's Javascript engine) uses mirrors for debugging Javascript code that runs in another object space.
This paper may help understanding the design of Java 6 annotation processing:
Gilad Bracha and David Ungar. Mirrors:
Design Principles for Meta-level
Facilities of Object-Oriented
Programming Languages. In Proc. of
the ACM Conf. on Object-Oriented
Programming, Systems, Languages and
Applications, October 2004.
The object of type javax.lang.model.element.AnnotationMirror represents an annotation in your code.
The declared type represents the annotation class.
Its element is the generic class (see http://java.sun.com/javase/6/docs/api/javax/lang/model/element/TypeElement.html for more information on that matter). The element might be the generic version of a class, like List, where as the declared type is the parametrized version, for instance List<String>. However I'm not sure it is possible to have annotations classes use generics and thus the distinction might be irrelevant in that context.
For instance lets say you have the following JUnit4 method:
#Test(expected = MyException.class)
public void myTest() {
// do some tests on some class...
}
The AnnotationMirror represents #Test(expected = NullPointerException.class). The declared type is the org.junit.Test class. The element is more or less the same as there are no generics involved.