What exactly is the point of bound properties? To me they seem to be a less type-safe version of events using EventObjects - it seems a bit weak to be using string equality checking for event.getPropertyName().
Why would you use one over the other?
The whole point of Java Beans is that a system (GUI Builder, in particular) can examine a Java Bean and configure it without any previous knowledge of that component.
Although this is fairly cool, it's really only useful in this specific situation and these days annotations would work MUCH better.
So the reason they use bound properties was simply to support this drop-in GUI component technology, and I wouldn't really prefer it over events unless you need to support a reflective gui-building system.
Response to #Mike rodent
Let's say you allow your user to create a class that you will control. This class has a "Main" and can handle a couple events.
Normally you have your user do something like this:
class UserClass(someClass) {
void mainMethod() {
someClass.addEventListener(new EventListener() {
public void eventsHappen(Event e){
event1(e)
}
}
}
someClass.addDifferentEventListener(new DifferentEventListener() {
public void eventsHappen(DifferentEvent e){
event2(e)
}
}
}
}
public void event1(Event e) {
//java code for event 1
}
public void event2(DifferentEvent e) {
// java code for event 2
}
}
Anyway, you get the idea. Of course, you assume that this class is registered somewhere--probably in an xml/config file. You read it, instantiate it and execute the mainMethod(defined by agreement or by interface) and it registers itself and starts getting calls to the event handlers.
Now here's how you can accomplish the same thing with annotations: (You might recognize the pattern--it's pretty much how Junit annotates tests.)
class UserClass() {
#Event1
void event1Method(Event e) {
event1's code
}
#Event2
void event2Method(AnotherEvent e) {
event2's code
}
}
This is much more straight-froward and removes most of the boilerplate, and it also removes the need for an agreement or interface, annotations are more clearly defined and independant. (You don't actually even NEED the event annotations if you care to inspect the parameters being passed into the methods, but dragons lie in that general direction).
You still need the class registered somewhere, but this time you just scan each method for your event annotations and register them yourself. Since it's only a few lines of code to read and process a class like this, why restrict this pattern to unit testing?
Another thing I found really neat, I used this pattern for Groovy classes that were "plugged-in" to my Java program. Since I was compiling all the classes in a given directory anyway, scanning for annotations was trivial.. The effect to the user is that he drops in (or edits) a properly annotated groovy text file and my code immediately compiles, integrates and starts calling their event handlers.
I think that JavaBeans specification was designed with generic object handling in mind. By example, putting a JavaBean in a IDE and using a visual property editor to configure it. In that case the IDE will use the general PropertyChangeEvent and so on.
Or if you want to copy equal named properties from a bean to another... it's another case of bean use (BeanUtils class).
But, if you plan to do specific things, as Noel Ang says I'd recommend strong-typing.
JavaBeans is a specification. It defines a bound property as that whose modification results in a notification being emitted, and a PropertyChangeEvent is the sanctioned notification entity.
So the putative JavaBeans-spec bean editor is supposed to listen for PropertyChangeEvents. Beyond the need to work with that spec, I wouldn't use it, myself.
Related
I am trying to achieve something similar to the C# preprocessor. I am aware that Java does NOT have the same preprocessor capabilities, and am aware that there are ways to achieve similar results using design patterns such as Factory. However, I am still interested in finding a solution to this question.
Currently, what I do is create a class that contains several static final boolean attributes, such as the following example:
public class Preprocessor
{
public static final boolean FULLACCESS = false;
}
I then use this in the following manner:
public ClassName getClassName()
{
if(Preprocessor.FULLACCESS)
{
return this;
}
else
{
return this.DeepCopy();
}
}
So far so good, this solves my problem (the example above is trivial, but I do use this in other instances where it is helpful). My question is, would there be a way to place the conditional around an entire method, so that the method itself would be unavailable given the correct "Preprocessor" variables? For example, I would like to be able to make a specific constructor available only for packages that are given "Full Access", as follows:
public ClassName()
{
// do things
}
if(FULLACCESS)
{
public ClassName(ClassName thing)
{
// copy contents from thing to the object being created
}
}
Again, I am aware of the limitations (or design decisions) of Java as a language, and am aware that in most circumstances this is unnecessary. As a matter of fact, I have considered simply creating these "extra" methods and placing the entire code of them within a conditional, while throwing an Exception if the conditional is not active, but that is a very crude solution that does not seem helpful to my programmers when I make these libraries available to them.
Thank you very much in advance for any help.
Edit:
To complement the question, the reason why I am attempting to do this is that by using exceptions as a solution, the IDE would display methods as "available" when they are actually not. However, again, it might just be a case of my being ignorant of Java.
The reasons for my wanting to do this are primarily so that I may have more than one public interface available, say, one restrictive where control is tighter within the methods, and one more permissive where direct alteration of attributes is allowed. However, I do also want to be able to actively remove portions of code from the .class, for instance, in a Product Line development approach where certain variants are not available.
Edit2.:
Furthermore, it is important to note that I will be generating the documentation conditionally as well. Therefore, each compiled version of the packages would have its own documentation, containing only that which is actually available.
Well, you can make it happen. A word of caution, though...
I can only think of one time when I thought this kind of approach was the best way, and it turned out I was wrong. The case of changing a class's public interface especially looks like a red flag to me. Throwing an exception when the access level isn't high enough to invoke the method might be more code-friendly.
But anyway, when I thought I wanted a preprocessor, what I did was to write one. I created a custom annotation to place on conditionally-available methods, grabbed a Java parser and wrote a little program that used the parser to find and remove methods that have the annotation. Then add that (conditionally) to the build process.
Because it turned out to be useless to me, I discarded mine; and I've never seen anyone else do it and publish it; so as far as I know you'd have to roll your own.
This answer is based partially on the comments you have left on the question and on Mark's answer.
I would suggest that you do this using Java interfaces which expose just the API that you desire. When you need a less restrictive API contract, extend an interface or create a separate implementation of an existing interface to get what you need.
public interface A
{
void f();
}
A above is your general API. Now you want to have some special extra methods to test A or to debug it or manipulate it or whatever...
public interface B extends A
{
void specialAccess();
}
Also, Java now supports default method implementations for interfaces which might be useful to you depending on how you implement your API. They take the following form...
public interface A
{
List getList();
// this is still only an interface, but you have a default impl. here
default void add(Object o)
{
getList().add(o);
}
}
You can read more about default methods on Oracle's page about it here.
In your API, your general distribution of it could include A and omit B entirely, and omit any implementations that offer the special access; then you can include B and special implementations for the special access version of the API you mentioned. This would allow plain old Java objects, nothing different to the code other than an extra interface and maybe an extra implementation of it. The custom part would just be in your packaging of the library. If you want to hand someone a "non-special" low-access version, hand them a jar that does not include B and does not include any possible BImplementation, possibly by having a separate build script.
I use Netbeans for my Java work, and I like to let it use the default build scripts that it auto generates. So if I were doing this and I were doing it in Netbeans, I would probably create two projects, one for base API and one for special-access API, and I would make the special-access one dependent on the base project. That would leave me with two jars instead of one, but I would be fine with that; if two jars bothered me enough I would go through the extra step mentioned above of making a build script for the special access version.
Some examples straight from Java
Swing has examples of this kind of pattern. Notice that GUI components have a void paint(Graphics g). A Graphics gives you a certain set of functionality. Generally, that g is actually a Graphics2D, so you can treat it as such if you so desire.
void paint(Graphics g)
{
Graphics2d g2d = Graphics2d.class.cast(g);
}
Another example is with Swing component models. If you use a JList or a JComboBox to display a list of objects in a GUI, you probably do not use the default model it comes with if you want to change that list over time. Instead, you create a new model with added functionality and inject it.
JList list = new JList();
DefaultListModel model = new DefaultListModel();
list.setModel(model);
Now your JList model has extra functionality that is not normally apparent, including the ability to add and remove items easily.
Not only is extra functionality added this way, but the original author of ListModel did not even need to know that this functionality could exist.
the only way in Java to reach that is to use preprocessor, for instance PostgresJDBC team uses java comment preprocessor for such manipulations, here is example from their Driver.java
//#if mvn.project.property.postgresql.jdbc.spec >= "JDBC4.1"
#Override
public java.util.logging.Logger getParentLogger() {
return PARENT_LOGGER;
}
//#endif
With Gradle you can manage your sources and I think that no preprocessor macros are no longer needed. Right now in src directory you have main/java with all sources but if you need specific methods in e.g. debug and release builds to do / or not specific things then create debug/java and release/java in src and put YourClass there. Note that by doing this you'll have to have YourClass in debug/java and release/java but not in main/java.
I'm designing an API that receives several event types all inheriting from a common base class. So lets say EventA and EventB inherit from BaseEvent
These events need to go trough several different processors.
So I though the visitor pattern would be a good choice here.
So the BaseEvent would look something like this:
public class BaseEvent implements Visitable {
void visit(Visitor visitor) {
visitor.visit(this);
}
}
So now I have an API that includes the Visitable and the Visitor types, but they are not really related to the API.
the processing is only done on the receiving side.
So I though about defining the API types without the Visitor interfaces and to define new types that include the visitors on the receiver of the events
But then I have to translate the API types to the new types and I don't see a way to do it without using instanseof for every event type
Does anyone see a solution for this?
Or maybe some other design that can solve the problem?
Thanks
Edit (Adding Some more info):
The events just hold information and on the receiver side they need to go through the processors.
I currently have 3 types of events (but that is likely to grow),
and 2 processors (this can also change but less likely)
I wanted to use the visitor pattern cause it forces me to add new methods to the processors when new events are added
If I just override the process() method for each type I will only catch errors in runtime when new events are added
I'm not sure what your use-case or architecture looks like, but I had a similar issue I think, with a trade routing system. There were events defined for routing a trade, getting acknowledgements, getting executions, etc. Events were only dumb objects, and there were processors with lots of if statements with instanceofs.
We decided to redesign the whole thing using "real" objects instead of events and processors. This means the "events" are no longer just holders of information, but they can "process themselves". Since they (at least in our use-case) had all the necessary information, they can actually process themselves better than one or multiple "external" processors.
There were multiple curious sideffects:
Dependencies became much clearer and easier.
We got rid of most of getters/setters, because asking an object for all of its information became unnecessary. This I found pretty cool.
So basically instead of a "bean" like this:
public class LimitOrderExecution ... {
private int executedAmount;
private int remainingAmount;
private BigDecimal executionPrice;
private Order order;
...more fields...
... setter / getter for everything ...
}
We now have:
public class LimitOrderExecution ... {
...fields...
public void apply() {
...applies itself using other objects...
}
}
There are several options:
instanceof
instanceof may not be that bad. Neither in regards of performance, nor from a coding-style POV. So why even use some workaround, if you don't need to?
Method overriding
Simply override the method for each Event that needs to be processed separately:
class EventReceiver{
void eventReceived(BaseEvent e){
}
void eventReceived(EventA e){
}
...
}
Same could of course be done for your visitor-pattern. Though the visitor-pattern would be rather superfluous here.
Another event-structure
If you don't want to distinguish your events by type, just add a variable that allows identification of the event without instanceof. Though that'd just be a workaround to the instanceof operator.
Context (Edit)
Some clarification was on demand, so I'll try to sum up what influences the question.
The goal of the project is to provide a certain functionality to programmers, most probably in the form of a library (a JAR with class files, I guess).
To use said functionality, programmers would have to conform to the constraints that must (should) be satisfied. Otherwise it won't function as expected (just like the locks from java.util.concurrent, that must be acquired / freed at the appropriate time and place).
This code won't be the entry point to the applications using it (ie, has no main).
There's a limited (and small) amount of operations exposed in the API.
Examples:
Think of a small game, where almost everything is implemented and managed by the already implemented classes. The only thing left for the programmer to do, is to write a method, or a couple of them, that describe what the character will do (walk, change direction, stop, inspect object). I would want to make sure that their methods (possibly marked with an annotation?) just walk, or changeDirection, or calculate diff = desiredValue - x, and not, say, write to some file, or open a socket connection.
Think of a transaction manager. The manager would be provided by this library, as well as some constant attributes of transactions (their isolation level, time-outs, ...). Now, the programmers would like to have transactions and use this manager. I would want to make sure that they only read, write, commit, or rollback on some resources, known to the manager. I wouldn't want them to launchRocket in the middle of the transaction, if the manager does not control any rockets to launch.
The Problem
I want to impose some invariants / restrictions / constraints on the body of a method (or group of methods), to be later implemented by some other programmer, in some other package/location. Say, I give them something along the lines of:
public abstract class ToBeExtended {
// some private stuff they should not modify
// ...
public abstract SomeReturnType safeMethod();
}
It is important (probably imperative), for the purposes of this project, that the method body satisfies some invariants. Or rather, it is imperative that the set of commands this method's implementation uses is limited. Examples of these constraints:
This method must not perform any I/O.
This method must not instantiate any unknown (potentially dangerous) objects.
...
Put another way:
This method can call the methods of a known (specific) class.
This method can execute some basic instructions (maths, assign local variables, ifs, loops...).
I've been looking through Annotations, and there seems to be nothing close to this.
My options so far:
Define some annotation, #SafeAnnotation, and apply it to the method, defining a contract with the implementer, that he will follow the rules imposed, or else the system will malfunction.
Define an Enum with the allowed operations. Instead of exposing the allowed methods, only a method is exposed, that accepts a list of these enum objects (or something similar to a Control Flow Graph?) and executes it, giving me the control of what can be done.
Example:
public enum AllowedOperations { OP1, OP2 }
public class TheOneKnown {
public void executeMyStuff (List<AllowedOperations> ops) {
// ...
}
}
My Question
Is there any feature in the language, such as annotations, reflection, or otherwise, allowing me to inspect (either at compile time or runtime) if a method is valid (ie, satisfies my constraints)?
Or rather, is there any way to enforce it to call only a limited set of other methods?
If not (and I think not), would this second approach be a suitable alternative?
Suitable, as in intuitive, well designed and/or good practice.
Update (Progress)
Having had a look at some related questions, I'm also considering (as a third option, maybe) following the steps given in the accepted answer of this question. Although, this may require some rethinking on the architecture.
The whole idea of using annotations to impose restrictions seems to require implementing my own annotation processor. If this is true, I might as well consider a small domain-specific language, so that the programmer would use these limited operations, later translating the code to Java. This way, I would also have control over what is specified.
Have a look at java policy files. I've not used them, and I'm not sure they'll fit your problem exactly, but with some digging into the docs they may be a fit. Here's a couple SO questions that may be of help
Limiting file access in Java
What is a simple Java security policy for restricting file writes to a single directory?
And here's some documentation on the policy file.
http://docs.oracle.com/javase/6/docs/technotes/guides/security/PolicyFiles.html
I think that the direction in this question is good.
Use a specific ClassLoader lo load the class. Beware, that they're an interesting type of horse, it usually happens that the class itself is loaded by a parent classloader. Probably you want some sort of UrlClassLoader, and the parent classloader would be set to the Root classloader It is not enough, though.
Use threads to avoid infinite loops (rather implementing Runnable than extending Thread, like there) - this may be unnecessary if you're not worrying about it.
Use SecurityManager to avoid java.io operations
In addition to the above, I recommend 2 options:
Give the method a controller, that would contain the functions it can call
For example:
public void foo(Controller ctrl) {
}
public class Controller {
public boolean commit();
public boolean rollback();
}
This can give the user a handle, what operations are allowed.
Use an Intent-like command pattern
In Android, the components of the system are quite closed. They cannot directly communicate to each other, they only can fire an event, that "this happened", or "I want to do that".
This way the set of the usable commands are not restricted. Usually, if the methods do only small business logic, that is enough.
You can restrict the classes used by untrusted code with a custom class loader:
public class SafeClassLoader extends ClassLoader {
Set<String> safe = new HashSet<>();
{
String[] s = {
"java.lang.Object",
"java.lang.String",
"java.lang.Integer"
};
safe.addAll(Arrays.asList(s));
}
#Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
if (safe.contains(name)) {
return super.loadClass(name, resolve);
} else {
throw new ClassNotFoundException(name);
}
}
}
public class Sandboxer {
public static void main(String[] args) throws Exception {
File f = new File("bin/");
URL[] urls = {f.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls, new SafeClassLoader());
Class<?> good = loader.loadClass("tools.sandbox.Good");
System.out.println(good.newInstance().toString());
Class<?> evil = loader.loadClass("tools.sandbox.Evil");
System.out.println(evil.newInstance().toString());
}
}
public class Good {
#Override
public String toString() {
return "I am good";
}
}
public class Evil {
#Override
public String toString() {
new Thread().start();
return "I am evil.";
}
}
Running this will result in
I am good
Exception in thread "main" java.lang.NoClassDefFoundError: java/lang/Thread
at tools.sandbox.Evil.toString(Evil.java:7)
at tools.sandbox.Sandboxer.main(Sandboxer.java:18)
Caused by: java.lang.ClassNotFoundException: java.lang.Thread
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 2 more
Of course, this assumes care is taken with the classes you white list. It also can't prevent denial of service stuff such as
while (true) {}
or
new long[1000000000];
Another alternative will be to use en embedded script interpreter, for example groovy one (https://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html) and to evaluate the third-party methods content at runtime with a pre-execution validation.
Advantage is that you will be able to limit access to only the variables you will bind for the script execution.
You could also write your own validation dsl and apply it, for example using custom annotation, to the method that will execute the script.
There are several design by contract libraries available for Java, but I'm not able to recommend one in particular. Java Argument Validation appears to be a lightweight solution, but again, I don't have first-hand experience with it.
I'm really rolling up my sleeves and trying to understand Java annotations for the first time, and have read the Sun, Oracle and Wikipedia articles on the subject. They're easy to understand conceptually, but am finding it difficult putting all the pieces of the puzzle together.
The following example is probably terrible engineering, but just humor me (it's an example!).
Let's say I have the following class:
public Widget
{
// ...
public void foo(int cmd)
{
switch(cmd)
{
case 1:
function1();
break;
case 2:
function2();
break;
case 3:
default:
function3();
break;
}
}
}
Now, somewhere else in my project, I have another class, SpaceShuttle, that has a method called blastOff():
public class SpaceShuttle
{
// ...
public void blastOff()
{
// ...
}
}
Now then, I want to configure an annotation called Widgetize so that any methods annotated with #Widgetize will have Widget::foo(int) invoked prior to their own call.
#interface Widgetize
{
int cmd() default 2;
}
So now let's revisit SpaceShuttle:
public class SpaceShuttle
{
// ...
#Widgetize(3)
public void blastOff()
{
// Since we pass a cmd of "3" to #Widgetize,
// Widget::function3() should be invoked, per
// Widget::foo()'s definition.
}
}
Alas, my questions!
I assume that somewhere I need to define an annotation processor; a Java class that will specify what to do when #Widgetize(int) annotations are encountered, yes? Or does this happen in, say, XML config files that get fed into apt (like the way ant reads build.xml files)?
Edit: If I was correct about these annotation processors in question #1 above, then how do I "map"/"register"/make known these processors to the apt?
In buildscripts, is apt typically ran before javac, so that annotation-based changes or code generation takes place prior to the compile? (This is a best practices-type question).
Thanks and I apologize for my code samples, they turned out a lot bulkier than I intended them to (!)
This sounds more like AOP (Aspect oriented programming) than annotations. The topics are often confused since AOP uses annotations to achieve it's goals. Rather than reinvent AOP from scratch, I would recommend looking up and existing AOP library such as AspectJ.
However, to answer your specific question, there are two possible approaches to achieve your goal.
Runtime Approach
This is the approach typically taken by container frameworks (like Spring). The way it works is that instead of instantiating your classes yourself, you ask a container for an instance of your class.
The container has logic to examine the class for any RuntimeAnnotations (like #Widgetize). The container will then dynamically create a proxy of your class that calls the correct Widgetize method first and then calls the target method.
The container will then return that proxy to the original requester. The requester will still thing he got the class (or interface) that he asked for and be completely unaware of the proxying behavior added by the container.
This is also the behavior used by AspectJ.
Enhancement Approach
This is the approach taken by AspectJ. To be honest, I don't know a lot of the details of how it works. Somehow, AspectJ will scan your class files (the byte code), figure out where the annotations are, and then modify the byte code itself to call the proxy class instead of the actual class.
The benefit of this approach is that you don't need to use a container. The drawback is that you now have to do this enhancement step after you compile your code.
I assume that somewhere I need to
define an annotation processor; a Java
class that will specify what to do
when #Widgetize(int) annotations are
encountered, yes? Or does this happen
in, say, XML config files that get fed
into apt (like the way ant reads
build.xml files)?
In Java 1.6, the standard way to define annotation processors its through the ServiceLoader SPI.
In buildscripts, is apt typically ran
before javac, so that annotation-based
changes or code generation takes place
prior to the compile? (This is a best
practices-type question).
APT must take place before compilation, as it operates on source files (actually on syntax trees).
I use method interceptors often with Hibernate. Hibernate requires that a transaction be started and committed round every query. Rather than have lots of duplicate code I intercept every Hibernate method and start the transaction in the interceptor.
I use AOP Alliance method interceptors in conjunction with Google Guice for this. Using these you use your Widgetise annotation and then use Guice to say where you see this annotation use this method interceptor. The following Guice snippet does this.
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), new TransactionalInterceptor);
The interceptor catches the method, you can then call foo and then the tell the method interceptor to proceed with invocation of the original method. For example (in a simplified form):
public class Interceptor implements MethodInterceptor {
//PUT ANY DEPENDENCIES HERE IN A CONSTRUCTOR
public Object invoke(MethodInvocation invocation) throws Throwable {
//DO FOO HERE
result = invocation.proceed();
return result;
}
}
This might be a little confusing and it took me a while to get my head around but it is quite simple once you understand it.
It seems that the basis of your confusion is an incorrect belief that Annotations are something more than just Metadata. Check out this page from the JSE 1.5 language guide. Here is a relevant snippet:
Annotations do not directly affect
program semantics, but they do affect
the way programs are treated by tools
and libraries, which can in turn
affect the semantics of the running
program. Annotations can be read from
source files, class files, or
reflectively at run time.
In your code
#Widgetize(3)
public void blastOff()
does not cause Widget::function3() to execute (asside: in java we reference a member as Widget.function3()) The annotation is just the equivalent of a machine-readable comment (i.e. metadata).
Annotations can be processed both at compile time and at runtime. To process them at runtime requires using the reflection API, which will have a performance impact if it's not done smartly.
It's also possible to process annotations at compile time. The goal is to generate a class which can then be used by your code. There is a specific interface annotation processors have to satisfy, and they have to be declared in order to be executed.
Take a look at the following article for an example which is structurally simple to your use case:
Annotation processing 101
What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?
What are their typical usages?
Are they unique to Java? Is there a C++ equivalent?
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks.
Oracle has a good explanation of the concept and its meaning in Java on their site.
Also, are they unique to Java, is there a C++ equivalent?
No, but VB and C# have attributes which are the same thing.
Their use is quite diverse. One typical Java example, #Override has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.
Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate (de)serialization information for classes, determine the memory layout of structures and declare function imports from legacy libraries (among others). They also control how the IDE form designer works.
/EDIT: Attributes on classes are comparable to tag interfaces (like Serializable in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.
Anders gives a good summary, and here's an example of a JUnit annotation
#Test(expected=IOException.class)
public void flatfileMissing() throws IOException {
readFlatFile("testfiles"+separator+"flatfile_doesnotexist.dat");
}
Here the #Test annotation is telling JUnit that the flatfileMissing method is a test that should be executed and that the expected result is a thrown IOException. Thus, when you run your tests, this method will be called and the test will pass or fail based on whether an IOException is thrown.
Java also has the Annotation Processing Tool (apt) where not only you create annotations, but decide also how do these annotations work on the source code.
Here is an introduction.
To see some cool stuff you can do with Annotations, check out my JavaBean annotations and annotation processor.
They're great for generating code, adding extra validations during your build, and I've also been using them for an error message framework (not yet published -- need to clear with the bosses...).
The first thing a newcomer to annotations will ask about annotations is: "What is an annotation?" It turns out that there is no answer to this question, in the sense that there is no common behavior which is present in all of the various kinds of java annotations. There is, in other words, nothing that binds them together into an abstract conceptual group other than the fact that they all start with an "#" symbol.
For example, there is the #Override annotation, which tells the compiler to check that this member function overrides one in the parent class. There is the #Target annotation, which is used to specify what kinds of objects a user defined annotation (a third type of construct with nothing in common with other kinds of annotation) can be attached to. These have nothing to do with one another except for starting with an # symbol.
Basically, what appears to have happened is that some committee responsible for maintaining the java language definition is gatekeeping the addition of new keywords to the java language, and therefore other developers are doing an end run around that by calling new keywords "annotations". And that's why it is hard to understand, in general what an annotation is: because there is no common feature linking all annotations that could be used to put them in a conceptual group. In other words, annotations as a concept do not exist.
Therefore I would recommend studying the behavior of every different kind of annotation individually, and do not expect understanding one kind of annotation to tell you anything about the others.
Many of the other answers to this question assume the user is asking about user defined annotations specifically, which are one kind of annotation that defines a set of integers or strings or other data, static to the class or method or variable they are attached to, that can be queried at compile time or run time. Sadly, there is no marker that distinguishes this kind of annotation from other kinds like #interface that do different things.
By literal definition an annotation adds notes to an element. Likewise, Java annotations are tags that we insert into source code for providing more information about the code. Java annotations associate information with the annotated program element. Beside Java annotations Java programs have copious amounts of informal documentation that typically is contained within comments in the source code file. But, Java annotations are different from comments they annotate the program elements directly using annotation types to describe the form of the annotations. Java Annotations present the information in a standard and structured way so that it could be used amenably by processing tools.
When do you use Java's #Override annotation and why?
The link refers to a question on when one should use the override annotation(#override)..
This might help understand the concept of annotation better.Check out.
Annotations when it comes to EJB is known as choosing Implicit middle-ware approach over an explicit middle-ware approach , when you use annotation you're customizing what you exactly need from the API
for example you need to call transaction method for a bank transfer :
without using annotation :
the code will be
transfer(Account account1, Account account2, long amount)
{
// 1: Call middleware API to perform a security check
// 2: Call middleware API to start a transaction
// 3: Call middleware API to load rows from the database
// 4: Subtract the balance from one account, add to the other
// 5: Call middleware API to store rows in the database
// 6: Call middleware API to end the transaction
}
while using Annotation your code contains no cumbersome API calls to use the middle-
ware services. The code is clean and focused on business logic
transfer(Account account1, Account account2, long amount)
{
// 1: Subtract the balance from one account, add to the other
}