检查类对象是否是Java中另一个类对象的子类 [英] Check if a Class Object is subclass of another Class Object in Java

查看:400
本文介绍了检查类对象是否是Java中另一个类对象的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java的反射API,并尝试处理一些字段.现在,我要确定字段的类型.字符串很简单,只需执行myField.getType().equals(String.class).其他非派生类也是如此.但是,如何检查派生类?例如. LinkedList作为List的子类.我找不到任何isSubclassOf(...)extends(...)方法.我需要遍历所有getSuperClass()并自己找到我的超级班吗?

I'm playing around with Java's reflection API and trying to handle some fields. Now I'm stuck with identifying the type of my fields. Strings are easy, just do myField.getType().equals(String.class). The same applies for other non-derived classes. But how do I check derived classes? E.g. LinkedList as subclass of List. I can't find any isSubclassOf(...) or extends(...) method. Do I need to walk through all getSuperClass() and find my supeclass by my own?

推荐答案

您需要此方法:

boolean isList = List.class.isAssignableFrom(myClass);

通常,List(以上)应替换为superclass,而myClass应替换为subclass

where in general, List (above) should be replaced with superclass and myClass should be replaced with subclass

来自

确定此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是该类或接口的超类或超接口.如果是,则返回true;否则,返回否则返回false.如果此Class对象表示原始类型,则如果指定的Class参数正是此Class对象,则此方法返回true;否则,此方法返回true.否则返回false.

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

参考:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆