DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > “When a class with type parameters is not a parameterized class” – a Java Generics Puzzler

“When a class with type parameters is not a parameterized class” – a Java Generics Puzzler

Andrew Phillips user avatar by
Andrew Phillips
·
Apr. 22, 10 · Java Zone · Interview
Like (0)
Save
Tweet
26.63K Views

Join the DZone community and get the full member experience.

Join For Free

while recently fiddling with some more runtime generic type extraction for deployit , i was caught out by some unexpected behaviour by the reflection api. a check of the javadocs quickly revealed that i had once again been too hasty in relying on "common sense". still, the case seems sufficiently unintuitive to merit discussion.

in this case, the issue centres on the interplay between class.gettypeparameters and parameterizedtype . the gist of the code looks something like:

 
interface spying {}

// small class hierarchy
class person {}
class professional<p> extends person {}

class agent extends professional<spying> {}
class assassin extends professional {}
class bystander extends person {}

...

person jbond = new agent();
system.out.println("generic superclass type argument: " + trygetsuperclassgenerictypeparam(jbond));

person joepublic = new bystander();
system.out.println("generic superclass type argument: " + trygetsuperclassgenerictypeparam(joepublic));

person oddjob = new assassin();
system.out.println("generic superclass type argument: " + trygetsuperclassgenerictypeparam(oddjob));

...

type trygetsuperclassgenerictypeparam(object obj) {
class<?> clazz = obj.getclass();
class<?> superclass = clazz.getsuperclass();

// elvis would be preferred, but for the sake of clarity...
if (superclass.gettypeparameters().length > 0) {
return ((parameterizedtype) clazz.getgenericsuperclass()).getactualtypearguments()[0];
} else {
return null;
}
}


 

so...what happens?

trygetsuperclassgenerictypeparam is where the action happens. it seems fairly straightforward: see if the object's superclass is generic (i.e. takes type parameters) and, if so, cast its type representation to parameterizedtype to extract the actual value for the type parameter. if the superclass is not generic, simply return null.

when this code is run, the first two invocations of trygetsuperclassgenerictypeparam result in the expected:

generic superclass type argument: interface spying
generic superclass type argument: null

what about the third one? well, given the fact that we've omitted to specify a generic type parameter for professional we might assume 1 that we'd also get null. the actual output, however, is:

exception in thread "main" java.lang.classcastexception: java.lang.class cannot be cast to java.lang.reflect.parameterizedtype
at trygetsuperclassgenerictypeparam(...)

huh?

in order to figure out what's going on here, let's have a look at the javadoc for class.gettypeparameters:

returns an array of typevariable objects that represent the type variables declared by the generic declaration represented by this genericdeclaration object, in declaration order. returns an array of length 0 if the underlying generic declaration declares no type variables.

in other words, this is returning class-level information about the declaration of, in our case, the professional class, which of course does have a type parameter.
however, if we look at class.getgenericsuperclass 2 , which we invoke next, we find that it:

returns the type representing the direct superclass of the entity [...] represented by this class.

if the superclass is a parameterized type, the type object returned must accurately reflect the actual type parameters used in the source code.

here, the information returned is specific to the actual declaration of the class, which may (or may not, as in our case) specify type paramaters for its superclass.

and therein lies the problem: professional.class.gettypearguments looks at the declaration of the professional class, discovering a type argument, whereas assassin.class.getgenericsuperclass looks at the occurrence of professional in the declaration of assassin and discovers no type parameters. hence, it returns a class rather than a parameterizedtype and blows up our code.

ergo

to cut a long story short: if an object's superclass has type arguments as determined by class.gettypearguments that does not mean that object.getclass().getgenericsuperclass() will be a parameterizedtype.

footnotes
  1. read "i assumed" ;-)
  2. it's a pity that class.getgenericsignature , which determines the "generic or not" behaviour of class.getgenericsuperclass, is private, native and undocumented.
  • share/bookmark

from http://blog.xebia.com/2010/04/22/when-a-class-with-type-parameters-is-not-a-parameterized-class-a-java-generics-puzzler/

Java (programming language) Object (computer science) Javadoc Data structure Gist (computing) Extract IT

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Importance of Semantics for Data Lakehouses
  • SQL Database Schema: Beginner’s Guide (With Examples)
  • API Security Tools: What To Look For
  • My Sentiments, Erm… Not Exactly

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo