Archive

Posts Tagged ‘Hacks’

Returning the result of a JPA native query as a simple Map or POJO

July 14, 2016 Leave a comment

I’ve spent quite some time on StackOverflow to answer one simple question: Can I make a JPA NativeQuery return the results as a Map or as a simple POJO? The common consensus looks like it’s not possible. This is unfortunate, but sometimes when people say something cannot be done, I get fired up. And I’ve found a solution, even though it involves a little Hibernate-Vendor-lock-in and a detour.
Read more…

Categories: JPA Tags: , , , , ,

Hack of the day: Get a method-annotation’s default value

June 27, 2016 Leave a comment

So you have an annotation like this:

@Inherited
@Documented
@InterceptorBinding
@Retention(RUNTIME)
@Target({ METHOD, TYPE, FIELD })
public @interface Logged {

	@Nonbinding
	String value() default "debug";

	@Nonbinding
	String detailValue() default "trace";

}

But the source code is not under your control, so you can’t refactor it to use a public constant. How will you get any annotation method’s default value?
You could do it like this:

private String badWay() {
	final Method meth = Logged.class.getMethod("detailValue");
	final Logged annotation = meth.getAnnotation(Logged.class);
	return Level.valueOf(annotation.value());
}

But then, if someone from the outside refactored it and renamed the method, your compiler won’t notice and it will break at runtime, which is bad.
Here’s a way to perform the task with some introspection, given the annotation can be used on methods:

Logged defaultLogged; //lazily initialized, as reflection is slow

@Logged // annotation with default log level
private String defaultAnnotationDetailLogLevel() {
        if(defaultLogged == null}{
            class Local {};
            final Method meth = Local.class.getEnclosingMethod(); // this method
            defaultLogged = meth.getAnnotation(Logged.class);
        }
        return defaultLogged.detailValue();
}

In case the annotation will be changed to use any other method name, your compiler will notice immediately and you can fix the broken code before it slips through testing and hits production. Nifty!

Hack of the day: Unchecking checked exceptions.

April 29, 2010 9 comments

In my last blog I announced to write something about some nice reflection magic, but it turned out that I got a little short on time, so that blog isn’t ready yet. But to keep you entertained I’d like to write something about a little hack I’ve found and instead of Reflection magic, you can read about some wild Generics magic. Not bad either, isn’t it? This hack is also really helpful! Read more…