简体   繁体   中英

How to find the instance by the interface they implements?

I have 2 java classes extends from 2 interface which are inherit relationship like below:

interface Base{}
interface Sub extends Base{}

class BaseImpl implements Base{}
class SubImpl implements Sub{}

Then I have one Manager class to provide add and findByClass method.

class Manager{
    List<Object> list = new ArrayList<>();

    public void add(Object o){
        list.add(o);
    }

    public List<Object> findByClass(Class clazz){
        //todo: add find logic
    }
}

And I add instances of BaseImpl and SubImpl to Manager and want to query them by interface class as below: return BaseImpl and SubImpl when query by Base interface class and return SubImpl only when query by Sub interface class.

    Manager m = new Manager();
    m.add(new BaseImpl());
    m.add(new SubImpl());

    m.findByClass(Base.class); //return BaseImpl and SubImpl
    m.findByClass(Sub.class); //return SubImpl only!
    

My question is how to implement the findByClass method in Manager?

new BaseImpl().getClass();

This is a silly way to do BaseImpl.class - that one does not require a no-args constructor, does not require a non-abstract class, and doesn't create a pointless instance.

Class<? extends BaseImpl>

Similarly, needlessly complicated.

Just write:

Class<BaseImpl> base = BaseImpl.class;

How to get the inherit relationship from class instance?

base.getSuperclass() and base.getInterfaces() are the methods you want. You'd have to recursively call it all, repeatedly, until you have created a complete list of all types for both base and sub and then you can check if there is overlap.

This is a bizarre thing to want to do, so maybe you want to take a step back and explain why you think you need this. Trivially, all classes always share 'a relationship', as everything extends java.lang.Object .

If you merely want to know if eg SubImpl.class is a subtype of BaseImpl, there is a method for that:

System.out.println(BaseImpl.class.isAssignableFrom(SubImpl.class));
> true

You can use Class#getSuperClass() to get the superclass of a class:

System.out.println(SubImpl.class.getSuperClass() == BaseImpl.class); // true
System.out.println(new SubImpl().getClass().getSuperClass() == new BaseImpl().getClass()); // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM