Can you find all classes in a package using reflection?

前端 未结 27 2156
不知归路
不知归路 2020-11-21 05:24

Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)

27条回答
  •  情书的邮戳
    2020-11-21 05:43

    If you are merely looking to load a group of related classes, then Spring can help you.

    Spring can instantiate a list or map of all classes that implement a given interface in one line of code. The list or map will contain instances of all the classes that implement that interface.

    That being said, as an alternative to loading the list of classes out of the file system, instead just implement the same interface in all the classes you want to load, regardless of package and use Spring to provide you instances of all of them. That way, you can load (and instantiate) all the classes you desire regardless of what package they are in.

    On the other hand, if having them all in a package is what you want, then simply have all the classes in that package implement a given interface.

提交回复
热议问题