Archive for January, 2008

Fun with Java generics

Thursday, January 31st, 2008

Playing around with Spring beans and Hibernate, combined with inheritance of my domain and service classes (not an easy ride, I can tell you), I was trying to implement a generic service to cater for CRUD operations while, at the same time, keeping Spring’s autowiring facilities at bay…

So far, no luck. But in the process of implementing my generic class, I faced a problem that took me a while to circumvent. Consider the following classes:

  class A<T> {

    // reference to an instance of the B class
    public B b;

    public void doOp() {

  class B {

    * this method takes a class as parameter
    public void callOp(Class c) {
      // …

The code that is problematic (as you might have guessed with the use of italics) is the following:


Well… it just doesn’t compile!
Apparently, there is no language feature to simply refer to the parameterized type class.

However, there’s still a solution:

(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

As documented here: ParameterizedType.getActualTypeArguments()

Thought I would share the goodness…

Sphere: Related Content