Get the Class Name of a Field from reflection

2020-07-22 09:14发布

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?

4条回答
欢心
2楼-- · 2020-07-22 09:51

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()

查看更多
欢心
3楼-- · 2020-07-22 09:52
System.out.println("3. " + fld.getType().getCanonicalName()); 

results in:

3. java.lang.String
查看更多
forever°为你锁心
4楼-- · 2020-07-22 09:53

I guess I solved it,

Should have done this:

String stype = fld.getType().getName();
查看更多
Explosion°爆炸
5楼-- · 2020-07-22 09:58

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

查看更多
登录 后发表回答