class.isAssignableFrom() send false when not the same package

I'm using isAssignableFrom() Class method to determine if a class from an other application implements an interface or not. Thus I have the same interface in both "application" but not in the same package. And the method returns false when the package of both interfaces is not the same, but true otherwise.

Is that a normal behaviour ?


And the method returns false when the package of both interfaces is not the same, but true otherwise.

Is that a normal behaviour ?

Yes . The package name is part of the class (and interface ) name. When the interfaces are in different packages they have different names (and are thus, not the same).


JavaDoc for this method

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.

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion.

See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.

Parameters: cls - the Class object to be checked Returns: the boolean value indicating whether objects of the type cls can be assigned to objects of this class

In nutshell the method returns true only in case if variable with class = parameter cls can be cast(assigned) to variable with class = class .

    Set<Integer> set = new HashSet<>();
    SortedSet<Integer> sortedSet = new TreeSet<>();

    System.out.println(Set.class.isAssignableFrom(SortedSet.class)); // true
    System.out.println(SortedSet.class.isAssignableFrom(Set.class)); // false


    Set<Integer> set2 = sortedSet; // ok
    SortedSet sortedSet2 = set; // compilation error 

So, it's about the method itself.

Now about your case. You says that:

Thus I have the same interface in both "application" but not in the same package.

But in deed and not in name, you have two deferent interfaces. They may have similar names (but only similar, because package also part or class name), but it's really different classes and they cannot be cast. Oh, sorry, they could be cast one to another in case if they has same superclass (they extends the same interface).

You may simple check it, by changing Set and SortedSet to your interfaces.

链接地址: http://www.djcxy.com/p/57412.html

上一篇: isAssignableFrom,Extends / Implements

下一篇: class.isAssignableFrom()当不是相同的包时发送false