检查类是否实现给定类名称的接口

时间:2018-09-07 02:28:38

标签: java

给予

String className = "com.example.MyClass";

如何检查此类是否实现了特定的接口?

我尝试过

Class myClass = Class.forName(className);
if (myClass instanceof MyInterface) {}

if (myClass.isInstance(MyInterface.class)) {}

但都不起作用-显然Class对象不能继承我的接口

仅在给定类名的情况下检查类是否实现接口的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用Class.isAssignableFrom(Class)来做到这一点:

 /**
 * Undo all object associations and convert them back into their original IDs. 
 * @param object $data
 * @param array $callable
 */
public function flattenObject($data, $callable){
    $sorter = new SortingHelper;
    foreach($callable as $call){
        $getMethod = 'get'.ucfirst($call).'Id';
        $setMethod = 'set'.ucfirst($call).'Id';
        if(method_exists($data, $getMethod)){
            $found = $data->$getMethod();
            if(gettype($found) == 'object'){
                $result = $this->flatten($found, $callable);
                $data->$setMethod($result);
            }
        }
    }
    return $data;
}

/**
 * @param object $data 
 * @param array $callable
 */
private function flatten($data, $callable){
    for($i = 0; $i != count($callable); $i++){
        $getMethod = 'get'.ucfirst($callable[$i]).'Id';
        $setMethod = 'set'.ucfirst($callable[$i]).'Id';
        if(method_exists($data, $getMethod)){
            $result = $data->$getMethod();
            if(gettype($result) == 'object'){
                $data->$setMethod($result->getId());
            }
        }
    }
    return $data->getId();
}