0

There is a nice discussion of generics here

But they all talk about how the class can accept generic type variable. My question is rather on the generic type class definition.

The class is defined as

protected final <T> T getBeanFromSpringContext(String name, Class<T> requiredType) {
    if(springApplicationContext != null) {
        return springApplicationContext.getBean(name, requiredType);
    } else {
        return null;
    }
}

Now I understand that the return type is T. But then <T> before that is the type of the class modeled by this Class object. Why is this not <?> as I don't know the type?

And since the return type is T. Can this class return null as is mentioned above?

Community
  • 1
  • 1
Some Java Guy
  • 4,992
  • 19
  • 71
  • 108
  • 1
    btw, I prefer this single-line style: `return springApplicationContext == null ? null : springApplicationContext.getBean(name, requiredType);` – Bohemian Jan 06 '12 at 10:37

1 Answers1

2

The <T> before that is a declaration saying that the method is generic, and it has a type parameter T—that is, it's a definition of a type variable.

It could be a bit different:

protected final <T extends Collection> T getBeanFromSpringContext(String name, Class<T> requiredType) {
    if(springApplicationContext != null) {
        return springApplicationContext.getBean(name, requiredType);
    } else {
        return null;
    }
}

That will not only say that you have a type parameter, but would also put some constraints, "bounds", on its values.

Update: now, on the null part. Unfortunately, all the non-primitive types mean "this type or null" in Java. So yes, you can always return null. And you can always get an NPE.

An obligatory Angelika Langer's FAQ link

alf
  • 8,377
  • 24
  • 45