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
如对本文有疑问, 点击进行留言回复!!
荐 面试官:kafka日志段如何读写都不知道,好意思说精通Kafka吗?
荐 如何写出一份“有理有据使人信服”的Android项目设计文档
荐 灵魂一问,Android中有代替HashMap的方法吗?
intent.setFlag的参数 FLAG_ACTIVITY_CLEAR_TASK 说明
网友评论