java子类与父类的判断(instanceof与isAssignableFrom)

java子类与父类的判断(instanceof与isAssignableFrom)_第1张图片

ResourceHttpRequestHandler 为子类
WebContentGenerator为父类

instanceof

判断一个对象是否是某个类的子类或当前类

		WebContentGenerator w = new WebContentGenerator() {
            @Override
            protected String getAllowHeader() {
                return super.getAllowHeader();
            }
        };
        ResourceHttpRequestHandler r = new ResourceHttpRequestHandler();
        // a instanceof b 判断a是否是b的子类或当前类
        System.out.println(r instanceof WebContentGenerator);//true
        System.out.println(ResourceHttpRequestHandler.class.newInstance() instanceof WebContentGenerator);//true
        System.out.println(r instanceof ResourceHttpRequestHandler);//true
        System.out.println(ResourceHttpRequestHandler.class.newInstance() instanceof  ResourceHttpRequestHandler);//true
        System.out.println(ResourceHttpRequestHandler.class.isInstance(w));//false
        System.out.println(WebContentGenerator.class.isInstance(r));//true
        System.out.println(w instanceof ResourceHttpRequestHandler);//false

isAssignableFrom

判断一个类是否是另一个类的父类或当前类

		System.out.println(ResourceHttpRequestHandler.class.isAssignableFrom(WebContentGenerator.class));//false
        System.out.println(WebContentGenerator.class.isAssignableFrom(ResourceHttpRequestHandler.class));//true
        System.out.println(WebContentGenerator.class.isAssignableFrom(WebContentGenerator.class));//true

你可能感兴趣的:(技巧,java)