вы можете использовать 'instanceof'
public class Test {
private static void doSomething(final Object o){
if(o instanceof Number){
System.out.println("it's a number!");
}
System.out.println("canonical class : "+o.getClass().getCanonicalName());
}
public static void main(String[] args) {
Number n = new Integer(10);
doSomething(n);
}
}
распечатывает
it's a number!
canonical class : java.lang.Integer
Другой вариант - рекурсивная проверка суперклассов
public class Test {
private static Class<?> doSomething(final Object o){
// assuming o is not null
Class<?> klass = getSuperClass(o.getClass());
return klass;
}
private static Class<?> getSuperClass(Class<?> klass){
// if super class is object or null break recursion
if(klass.getSuperclass() == null || klass.getSuperclass().equals(Object.class)){
return klass;
}
// keep looking higher up
return getSuperClass(klass.getSuperclass());
}
public static void main(String[] args) {
Number n = new Integer(10);
System.out.println("n is a "+doSomething(n).getCanonicalName());
Object o = new Integer(10);
System.out.println("o is a "+doSomething(o).getCanonicalName());
Number d = new Double(10.0d);
System.out.println("d is a "+doSomething(d).getCanonicalName());
String s = "10";
System.out.println("s is a "+doSomething(s).getCanonicalName());
Object so = "10";
System.out.println("so is a "+doSomething(so).getCanonicalName());
}
}
распечатывает
n is a java.lang.Number
o is a java.lang.Number
d is a java.lang.Number
s is a java.lang.String
so is a java.lang.String