反射获取接口的所有实现类
程序员文章站
2022-05-07 19:15:22
添加依赖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 pu...
添加依赖
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">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();
}
}
}
本文地址:https://blog.csdn.net/ZZL23333/article/details/107162181
推荐阅读
-
Java通过接口实现匿名类的实例代码
-
Java之反射第十八天( --反射----类的加载--获取对象属性( 成员变量和方法)-- 构造方法 )
-
c# 实现IComparable、IComparer接口、Comparer类的详解
-
asp.net实现利用反射,泛型,静态方法快速获取表单值到Model的方法
-
C#获取Word文档中所有表格的实现代码分享
-
iOS实现封装一个获取通讯录的工具类详解
-
C#实现获取文本文件的编码的一个类(区分GB2312和UTF8)
-
Java 采用反射获取class属性值的实现代码
-
详解JAVA中的Collection接口和其主要实现的类
-
java反射之获取类的信息方法(推荐)