Java如何获取接口所有的实现类
目录
- Java获取接口所有的实现类
- 反射获取接口的所有实现类
- 总结
Java获取接口所有的实现类
最近因业务需求,要实现NodeRed服务后端化,为使各个节点的解析进行插件化(NodeRed各个节点也是插件化,安装插件即可使用) ,后端不得不动态加载解析NodeRed节点json,用一个接口来统一管理。
import cn.hutool.core.util.ClassUtil; import java.util.*; /** * 此类用来解析NodeRed服务器的json串 */ public class NodeRedParseUtil { public static void main(String[] args) throws IllegalAccessException, InstantiationException { //获取所有的模型实现类 Set<Class<?>> classes = ClassUtil.scanPackageBySuper("com.ciih.nodred.plugins", NodeRedModel.class); Map<String, NodeRedModel> map = new HashMap<>(classes.size()); for (Class<?> aClass : classes) { //实例化 Object o = aClass.newInstance(); System.out.println(); if (o instanceof NodeRedModel) { NodeRedModel nodeRedModel = (NodeRedModel) o; map.put(nodeRedModel.getType(), nodeRedModel); } } } }
反射获取接口的所有实现类
添加依赖
implementation 'org.reflections:reflections:0.9.12'
接口
package com.example.myapplication.people; public interface IPeople { String say(); }
实现类
package com.example.myapplication.people; public class Student implements IPeople{ @Override public String say() { return "I am a student"; } }
package com.example.myapplication.people; public class Teacher implements IPeople{ @Override public String say() { return "I am a teacher"; } }
工具类
package com.example.myapplication; import android.net.IpPrefix; import com.example.myapplication.people.IPeople; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.reflections.Reflections; public class Utils { public static Map<String,Class> getAllIPeopleImpl(){ Reflections reflection=new Reflections("com.example.myapplication.people"); Map<String,Class> map=new HashMap<>(); Set<Class<? extends IPeople>> set=reflection.getSubTypesOf(IPeople.class); for(Class c:set){ map.put(c.getSimpleName(),c); } return map; } }
测试类
package com.example.myapplication; import com.example.myapplication.people.IPeople; import java.util.Map; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing" rel="external nofollow" >Testing documentation</a> */ public class ExampleUnitTest { @Test public void test() { Map<String, Class> map = Utils.getAllIPeopleImpl(); try { for (String str : map.keySet()) { Object people = map.get(str).newInstance(); if(people instanceof IPeople){ System.out.println(str); System.out.println(((IPeople) people).say()); } } } catch (IllegalAccessException | InstantiationException e) { e.printStackTrace(); } } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)