DZone
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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Java String: A Complete Guide With Examples
  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java
  • NullPointerException in Java: Causes and Ways to Avoid It

Trending

  • AI Agents: A New Era for Integration Professionals
  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  • When Airflow Tasks Get Stuck in Queued: A Real-World Debugging Story
  • How to Introduce a New API Quickly Using Micronaut
  1. DZone
  2. Coding
  3. Java
  4. “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

By 
Andrew Phillips user avatar
Andrew Phillips
·
Apr. 22, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
28.3K 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.

Related

  • Java String: A Complete Guide With Examples
  • Generics in Java and Their Implementation
  • Speeding Up Large Collections Processing in Java
  • NullPointerException in Java: Causes and Ways to Avoid It

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!