This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How get "base class" of an array?  RSS feed

 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a method that takes an Object and the object can be an array (say Integer[][]), how would I find out that the base class is Integer? Doing a getClass() returns the Integer[][] class not Integer class. So I can't just use ".equals()" to see or even instanceof. how do I find the array's base class?

For example:
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you look at the (admittedly large) java.lang.Class API? The methods you're looking for are called "isArray()" and "getComponentType()". When you get a Class object, call isArray() in a loop; each time isArray() returns true, replace your class object with getComponentType()'s return value. Eventually isArray() returns false; then you're holding the class you're after.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!