1
public static void printType(Object o){
  type = **someWayToDeduceTheObjectType()**
  fields = type.getDeclaredFields()
  System.out.println("The type of the object is : " + type);
  System.out.println("The fields of this type of class is : " + fields);
}

Is it possible to infer the object type of a passed object from a generic reference type?

If not, what is the reason?

I assume this is not possible, because of the existence of casting, but I can't pinpoint the exact reason.

EDIT: I'm not referring to instanceof operator here. Assume I don't have a list of Types to compare with.

chamilad
  • 1,619
  • 3
  • 23
  • 40

1 Answers1

2

It's quite possible - you just call getClass():

public static void printType(Object o){
  type = o.getClass();
  fields = type.getDeclaredFields()
  System.out.println("The type of the object is : " + type);
  System.out.println("The fields of this type of class is : " + fields);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350