欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-11-30 18:57:00
添加依赖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