getClass() returning java.lang.Class [Reflection]

So upon getting the parameter(s) for a method via Reflection:

Class<?>[] params = m.getParameterTypes();

And assuming I'm looping through methods and looking for a method with only one parameter:

if(params.length > 1) {
     continue;
}

Then getting that parameter if the length of the params array is 1:

Class<?> par = params[0];

When I try printing out the parameter's class with the getClass() method, it returns java.lang.Class.

However, when I get the superclass with the getSuperclass() method, it returns the superclass.

So for example:

System.out.println(par.getClass());
System.out.println(par.getSuperclass());

Assume the parameter of the method we have is a class called "PlayerDeathEvent", which extends the abstract "Event" class.

That being said, the output would be:

java.lang.Class
org.mypackage.Event

Is there a reason why this is occurring? I found a way around this with getCanonicalName, but I'm very curious as to why this occurs.

Upvotes: 2

Views: 4874

Answers (2)

Nivas
Nivas

Reputation: 18334

par is a object of Class here:

Class<?> par = params[0];

getClass is from java.lang.Object. It returns the class (type) of the object.

So if s is a String

String s = "test";

s.getClass returns String". By the same logic, par.getClass() returns Class.

getSuperClass, on the other hand, is defined java.lang.Class which returns the superclass of the class being represented.

So if s is a String, and c is a class that holds the reflective Class:

String s = "test";
Class c = s.getClass();

s.getClass returns String
c.getSuperClass returns Object because Object is Strings super class
c.getName returns String and
c.getClass returns Class


You are probably looking for getName()

Upvotes: 1

rgettman
rgettman

Reputation: 178263

The getClass() method is a method in Object that returns the Class object for the instance. You have a Class object, so getClass() returns the Class object for the Class class -- a different Class than what par is an instance of.

However, the getSuperclass() method, defined in Class, returns the Class object for the superclass of the class, not of the Class returned by getClass().

To get PlayerDeathEvent, call getName() instead.

System.out.println(par.getName());

Upvotes: 8

Related Questions