Fabian Zbinden
Fabian Zbinden

Reputation: 136

Get the real Class Type

If I do something like this:

String s = "hello";
Class<?> c = s.getClass();

Then c is acutally a Class but in there is a String. So how do I get a String Type back?

Because if I use: c.getClass() I get obviously a Class Type.

Upvotes: 1

Views: 383

Answers (2)

davidxxx
davidxxx

Reputation: 131396

First : you can get the class instance from an object as an instance of a class is associated to a class (whereas the presence of the getClass() method in the Object class) but it doesn't work in the other way as the class is not associated to a specific instance of.

Second : to get the type, you don't care whether an unbounded wildcard is specified or not in the Class declared type as generics are erased at runtime.
The thing that matters is that information about the class associated (here String) to the Class object is known by the Class object itself.
So for example, you can write the one or the second :

Class<? extends String> c = s.getClass();
Class<?> c = s.getClass();

And in any case you will be able to retrieve the type String as you invoke :

String typeName = c.getTypeName(); // --> java.lang.String
String name = c.getName(); // --> java.lang.String

Upvotes: 2

Amit Bera
Amit Bera

Reputation: 7325

So, Class<?> c will refer to the object of Class of Type String. Class<?> c basically has some metadata about the String class.

    String s = "hello";
    Class<?> c =  s.getClass();
    String s1 = (String) c.newInstance();

Edited:

So, there are several methods available on the Class object to retrieve the information about the Class :

    Class#getName() //the name of the class or interface represented by this object with package name
    Class#getSimpleName() // returns only the name of the Class

For example:

String s = "hello";
Class<?> c =  s.getClass();
System.out.println("Name : "+c.getName());
System.out.println("Simple Name: "+c.getSimpleName());
System.out.println("Canonical Name: "+c.getCanonicalName());
System.out.println("Type Name : "+c.getTypeName());

You will get the output:

Name : java.lang.String
Simple Name: String
Canonical Name: java.lang.String
Type Name : java.lang.String

Note: As you can see the same return value you are getting for different methods (like getCanonicalName, getCanonicalName etc), it may not be same always to know difference please the link I have provided below.

Appart from that there are several methods available on the Class object to get the metadata information about the class. Please follow the docs for more info.

Upvotes: 4

Related Questions