有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    如果只有类,则可以在运行时使用Class.isAssignableFrom()进行检查;如果有实例,则可以使用instanceof操作符进行检查

    至于编译时间,我不理解这个问题。为什么编写代码的人在编译时之前不知道

  2. # 2 楼答案

    代码:

    anotherClass.class.isAssignableFrom( someClass.class );
    

    如果还想检查另一个类是否为真实类(而不是接口),请添加对^{}的调用:

    !anotherClass.class.isInterface() && anotherClass.class.isAssignableFrom( someClass.class );
    

    例如:

    System.out.println( Number.class.isAssignableFrom( Integer.class )); // true
    

    请注意instanceof不适用于您,因为您没有实例,只有类

    摘自^{}的Javadoc:

    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.

  3. # 3 楼答案

    正如其他人已经建议的那样,签入运行时非常简单。然而,在编译时用一点技巧就可以做到这一点

    您可以使用泛型获得如下方法:

    public static <A, B extends A> void isExtends(Class<A> clazzA, Class<B> clazzB) {
        // empty
    }
    

    如果你想确定某个班级。类派生自另一个类。类,只需输入代码:

    isExtends(AnotherClass.class, SomeClass.class);
    

    编译器将帮助您验证某个类是否从另一个类扩展

    (但老实说,我想知道这在现实生活中是否真的有用:p)