views:

1427

answers:

7

I'm a little new to the Java 5 annotations and I'm curious if either of these are possible:

This annotation would generate a simple getter and setter for you.

@attribute
private String var = "";

The @NotNull annotation indicates that a variable connot be null so you don't have to write that boilerplate code every time.

/*
 * @param s @NotNull
 */
public void setString(String s){
    ...
}

Will either of these work? They seem like the first things I would write annotations for if I could. Since I don't see much about these when I read the docs I'm assuming that it's not really what annotations are about. Any direction here would be appreciated.

+4  A: 

Is there a way to use annotations in Java to replace accesssors?

In short, no, the Java 5/6 compiler does not support this and it would be difficult for third parties to add such support in a compiler-agnostic manner.

To get a better handle on annotations, I'd start with JUnit. If you write code for versions 3 (pre-annotations) and 4 (annotation-based), you quickly get a handle on how the framework replaced a contract based on naming patterns with one that was annotation-based.

For a more dramatic example, compare EJB 2 with EJB 3.

McDowell
+10  A: 

Annotation processing occurs on the abstract syntax tree. This is a structure that the parser creates and the compiler manipulates.

The current specification (link to come) says that annotation processors cannot alter the abstract syntax tree. One of the consequences of this is that it is not suitable to do code generation.

If you'd like this sort of functionality, then have a look at XDoclet. This should give you the code generation preprocessing I think you are looking for.

For your @NonNull example, JSR-305 is a set of annotations to enhance software defect detection, and includes @NonNull and @CheckForNull and a host of others.

Edit: Project Lombok solves exactly the problem of getter and setter generation.

jamesh
You can create a superclass... See http://code.google.com/p/javadude/wiki/Annotations
Scott Stanchfield
+4  A: 

The @attribute you are referring too cant work with annotations as they are now in Java (as jamesh pointed out).

What you are probably looking for is "properties" which dont exist yet in Java. But is is a very hot topic right now, and we might get them in Java 7 or maybe Java 8 (as I am still stuck on 1.4.2 it wont help me, but it might help you).

There was an interesting discussion allusion to implementing properties with annotations in the Java Posse episode #219.

Guillaume
Probably won't help me too much. I just left java 1.4, and that's only for this project. Ahh the bleeding edge of Oracle.
Jason Tholstrup
Lucky. I still have to use 1.2...
Bill K
+1  A: 

There is project named OVal and i think it does what you want. http://oval.sourceforge.net/

If i remeber right for advance thing AspectJ is needed, however simple check work without AspectJ. check it out.

There is also Hibernate Validator, check it out too :P

A: 

It's possible, just not where you're declaring them.

Check out http://code.google.com/p/javadude/wiki/Annotations.

I have a class annotated like

package sample;
import com.javadude.annotation.Bean;
import com.javadude.annotation.Property;
import com.javadude.annotation.PropertyKind; 

@Bean(properties={
    @Property(name="name"),
    @Property(name="phone", bound=true),
    @Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
})
public class Person extends PersonGen {}

And it generates the PersonGen class for you, containing getters/setters, etc

The processor also does quite a bit more. Note that I'm working on a new version of it that has a little API breakage from the current version

Scott Stanchfield
+4  A: 

Getters/Setters: Yes, it is possible. The project lombok (http://projectlombok.org/index.html) defines annotations for generating getters/setters and more.

NotNull: This is supported by findbugs and IdeaJ IDE, maybe others

Jirka-x1
A: 

Although they are sometimes useful, if you are seriously missing attributes then you are probably a little unsteady on the whole OO design thing.

The idea of OO Design is that methods are "Actions" where you are asking the object to do something for you--not just setting or getting a value--that's not an object, it's a structure.

If you think that the lack of attributes is a serious problem, I highly recommend that you try coding for a while without ever using setters and resisting getters.

It might be hard at first, but I bet at the end you'll have a firmer grasp on OO design principles.

(Note: There are rare situations where you must do "setter" type operations after the construction of an object--most commonly when you must create two objects that refer to each other. In this case I recommend something like the builder pattern where your setters must be called once and are protected from being called twice)

Bill K
I'll just have to disagree with you here. I often need to do more than set a property in a setter (null checks, other data constraint validations) and I make a practice of checking for null lists in getters and returning empty lists instead (among other sanity checks). Since I am in this habit, I prefer for them all to be set and got via the same mechanism, accessors. In addition, if you have other people interfacing with your code, changing the interface because you decide you want to do some validation after the fact will become very tiresome very quick. Thanks for judging though.
Jason Tholstrup
Setters automatically make your object mutable. Immutable is always preferable, so putting in setters by default is pretty much automatically a bad practice. Getters--meh, as I said, sometimes necessary but shouldn't be automatic. Also, if they are beyond trivial, then they are no longer setters and getters, they are full fledged methods--I love those!
Bill K
@Jason but, by the way, you're not alone. More people balk at this statement than just about any other. It usually takes seeing it a few times, thinking about it for a few months and implementing without them for a while before you really realize the benefits that your code derives from avoiding them.
Bill K
I understand where you are coming from here, but by the time you want to integrate with hibernate, XML serialization, web services, GWT and a dozen other things that by default work with accessors it's simply not worth it. I am also not "balking" at your statement. I am balking at the attitude of your response. Since I want this feature I must obviously have no grasp of OOP and I need to become refined like you. I understand the benefits of what you are saying, but there are a lot of drawbacks too (legacy code, frameworks, coworker attitudes). tl;dr; don't talk down to people.
Jason Tholstrup
@Jason Tholstrup I agree that it is difficult to integrate with other systems without accessors, I just think that is an indication of something missing in the java language.. Hibernate requiring getters and setters makes all your objects vulnerable and worse--and it also encourages people to program poorly. That's why systems are moving away from requiring the getter/setter hack from hell and towards annotations. If people make assertions that seem to me like a bad idea, I tend to say so. If you can prove to me that attributes are awesome, I'll stop recommending that people don't use them
Bill K
@Bill: While is partly agree, I am very fond of how it works in C#. For instance, it makes it possible to do things like `car1.color = car2.color = Blue`. Not to mention that it immensely helps debugging: In java, you have to inspect the private vars instead of just "browsing" the property hierarchy (the horrors of HashMap inspection...) Also, I don't think a language should remove important features just because they _can_ be misused by clueless programmers.
Martin Wickman
@Martin Wickman And what makes you want to do car1.color = car2.color = blue? How do you scale that to 3 cars? How do you change colors. Amazingly non-reusable--in fact the worst code you could possibly write. In fact, thanks--you really point up my exact point, if you are coding with good, reusable OO Code you're better off. What you really want is carCollection.setColor(newColor). Now you CAN say carCollection.color=newColor, but that kind of hides the fact that work is going on int the background which is great if you want to throw the next programmer off the scent...
Bill K
@Bill: Wow, we really are on complete opposite parts of the game here and I don't feel it is any reason to continue this. Java does not have properties, and I understand it may be a a bit odd if not used to having the syntax available. I would take a look at some other programming languages which do have them (C# and Scala springs to mind), how they are implemented and how people are using them, with excellent results (not to mention readable, clean code).
Martin Wickman