Araejay
Araejay

Reputation: 222

Get the Class Name of a Field from reflection

Im going round in circles on this.

I have a class Person, eg

public class Person {
String name = "";
}

Now, I would like to introspect this class instance & figure out what Class is name declared as.

So, name = String or java.lang.String

This is my Code:

'this' is an instance of Person.

try {
    String className = this.getClass().getName();
        Class cls = Class.forName(className);
        Field fieldlist[] = cls.getDeclaredFields();
        for (int i = 0; i < fieldlist.length; i++) {
           Field fld = fieldlist[i];
           int mod = fld.getModifiers();
           System.out.println("1. " + fld.toGenericString());
           System.out.println("2. " + fld.getName());
           System.out.println("3. " + fld.getGenericType() + "]");



           Object oj = fld.getType();

           // Says that 4: class java.lang.String

           System.out.println("4: " + oj.toString());
           Class c1 = oj.getClass();

           // Should throw Exception
           String stype = c1.getDeclaringClass().toString();
           System.out.println("5. " + stype);


        }
      }
      catch (Throwable e) {
         System.err.println(e);
      }

I managed to get to a part that states:

class java.lang.String

but I need it to be "java.lang.String"

Any ideas?

Upvotes: 3

Views: 11025

Answers (4)

Aung Aung
Aung Aung

Reputation: 227

I got the class name of a field by calling this f.getDeclaringClass().getSimpleName()

Upvotes: -1

Jayan
Jayan

Reputation: 18468

Try.. getType() and then getName()

 fld.getType().getName()

Edit:(Aften Green Days' comment) -- Note that fld.getType().getCanonicalName() will give same output in most cases. The output is different when innerclasses are used. Here is link came from search. Depending what you need to do with classname you may choose one of getName() or getCanonicalName()

Upvotes: 4

Araejay
Araejay

Reputation: 222

I guess I solved it,

Should have done this:

String stype = fld.getType().getName();

Upvotes: 0

Green Day
Green Day

Reputation: 664

System.out.println("3. " + fld.getType().getCanonicalName()); 

results in:

3. java.lang.String

Upvotes: 3

Related Questions