当前位置: 移动技术网 > 移动技术>移动开发>Android > 反射获取接口的所有实现类

反射获取接口的所有实现类

2020年07月09日  | 移动技术网移动技术  | 我要评论

添加依赖

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网