Thursday, May 24, 2012

A lot of work with CDI

I didn't write a lot of posts these days, that's because CDI is taking my full attention.
CDI is quite a nice invention for Java EE but despite my first thought, it's not just about injection.
All those
  • Interceptors
  • Decorators
  • Portable Extensions
  • ...
are nice things. It's just that you have to learn about them. But I have to thank Gavin King and the JSR-299 Expert Group for writing a very good and understandable specification. If you want to learn more about CDI and you're tired of all those tutorials on the internet, try to take a look at the specification. You can find it here. They put some really good examples into the first chapters, too.
So, have with injection ;)

Tuesday, May 15, 2012

@Nonbinding

I experiment recently a lot with CDI and one point I stumbled upon were the return values of my annotation functions.
Consider an annotation like this:

@Qualifier
@Retention(...)
@Target(...)
public @interface MyInterface{
 String value();
}

I tried to combine this annotation with a producer method and to use the value in the method (by asking the InjectionPoint for its value). Every time my Eclipse tried to deploy the .war it showed me an error.
After a while I found out that the only way to evade this, is to use the annotation @Nonbindung.
The altered annotation looks like this:

@Qualifier
@Retention(...)
@Target(...)
public @interface MyInterface{
 @Nonbinding
 String value();
}


Maybe I didn't read the spec good enough, but it took me a while to find that out.
So I hope you guys won't have the same problem like me ;)

Thursday, May 3, 2012

new vs. valueOf() in Java primitive wrappers

Did you ever take a close look at the Javadoc which is written at, for example, Integer.valueOf()?

No? Ok, I'll tell you ;)

It says you should prefer using the valueOf() method instead of using Integer's constructor. You'll find the same annotation at all the other wrapper classes for the primitive types in Java. (in Double, the Javadoc says the same, but double doesn't have a cache, weird...)

The reason is that Java will cache some values, so the VM won't create a lot of new objects.
I cannot imagine a certain case, when I explicitly need a new Integer or something similar (maybe in a JUnit-Test). A friend of mine mentioned when it's the key of a WeakHashMap.

So the next time you want to type new Integer(...), consider using Integer.valueOf(...) ;)

 

Copyright @ 2013 Wrong tracks of a developer.

Designed by Templateiy