如何在Java中以编程方式获取接口的所有实现列表?

编程入门 行业动态 更新时间:2024-10-25 02:18:47
本文介绍了如何在Java中以编程方式获取接口的所有实现列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以用反射或类似的东西来做吗?

Can I do it with reflection or something like that?

推荐答案

我一直在寻找一段时间似乎这是一个总结:

I have been searching for a while and there seems to be different approaches, here is a summary:

  • 反射 如果您不介意添加依赖项,那么库很受欢迎。它看起来像这样:

  • reflections library is pretty popular if u don't mind adding the dependency. It would look like this: Reflections reflections = new Reflections("firstdeveloper.examples.reflections"); Set<Class<? extends Pet>> classes = reflections.getSubTypesOf(Pet.class);

  • ServiceLoader (根据erickson的回答)它会看起来像这样:

  • ServiceLoader (as per erickson answer) and it would look like this:

    ServiceLoader<Pet> loader = ServiceLoader.load(Pet.class); for (Pet implClass : loader) { System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat }

    请注意,为此,您需要定义 Pet 作为ServiceProviderInterface(SPI)并声明其实现。你可以通过在 resources / META-INF / services 中创建一个名为 examples.reflections.Pet 的文件来做到这一点。声明其中 Pet 的所有实现

    Note that for this to work you need to define Petas a ServiceProviderInterface (SPI) and declare its implementations. you do that by creating a file in resources/META-INF/services with the name examples.reflections.Pet and declare all implementations of Pet in it

    examples.reflections.Dog examples.reflections.Cat

  • 包级注释。这是一个例子:

    Package[] packages = Package.getPackages(); for (Package p : packages) { MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class); if (annotation != null) { Class<?>[] implementations = annotation.implementationsOfPet(); for (Class<?> impl : implementations) { System.out.println(impl.getSimpleName()); } } }

    和注释定义:

    @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PACKAGE) public @interface MyPackageAnnotation { Class<?>[] implementationsOfPet() default {}; }

    您必须在名为 package-info.java 。以下是示例内容:

    and you must declare the package-level annotation in a file named package-info.java inside that package. here are sample contents:

    @MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class}) package examples.reflections;

    请注意,只有当时ClassLoader已知的软件包才能通过调用 Package.getPackages()。

    Note that only packages that are known to the ClassLoader at that time will be loaded by a call to Package.getPackages().

    此外,还有基于URLClassLoader的其他方法将始终限制为已经加载的类,除非您执行基于目录的搜索。

    In addition, there are other approaches based on URLClassLoader that will always be limited to classes that have been already loaded, Unless you do a directory-based search.

  • 更多推荐

    如何在Java中以编程方式获取接口的所有实现列表?

    本文发布于:2023-11-28 13:23:23,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1642584.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:中以   接口   方式   如何在   列表

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!