有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取方法集合

我有一些助手类用于测试,其结构如下:

public class EntitiesForTest {
    public static Entity firstEntity() {
        return new Entity(/*some dummy data*/)
    }

    public static Entity secondEntity() {...}
    ...
    public static Entity nthEntity() {...}

    public static List<Entity> allEntities() {???}
}

这些类的目的是让一些对象来测试我的系统的上层,比如让一些JSON数据来测试REST服务。这项技术不是我的,而是我正在学习的一门在线课程,非常酷

我想知道是否有一种方法可以基于类的静态继承方法和集合框架构建List<Entity>。我可以做Arrays.asList(/*call the methods one by one comma-separated*/),但必须有一种更智能、功能更强大、可重用的方法来做这件事

提前感谢您的回答


共 (4) 个答案

  1. # 1 楼答案

    “现代”方式

    public static List<Entity> getEntities() {
        return Arrays.stream(Foo.class.getMethods()).
                filter(method -> method.getReturnType() == Entity.class && 
                                 Modifier.isStatic(method.getModifiers())).
                map(method -> {
                    try {
                        return (Entity)method.invoke(null);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        throw new RuntimeException(e); // exceptions in streams... lol
                    }
                }).
                collect(Collectors.toList());
    }
    

    我希望我知道一种避免演员阵容的方法,但我现在还不清楚

  2. # 2 楼答案

    这个答案有几个假设:

    • 您不需要单独的方法(firstEntitysecondEntity,等等)
    • 这些实体只保存数据,创建和保存这些数据并不昂贵
    • 您不需要修改它们,这意味着您不会多次调用您的方法

    这些可能不成立,因为我们没有Entity的定义或它的使用方式

    总之,我只是删除了你的方法

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class EntitiesForTest {
        private static final List<Entity> entities = Arrays.asList(
               new Entity(),
               new Entity(),
               new Entity()
        );
    
        public static Entity allEntities(int n) {
            return entities.get(n);
        }
    
        public static List<Entity> allEntities() {
            return Collections.unmodifiableList(entities);
        }
    }
    
  3. # 3 楼答案

    可能使用函数方式(在Java8中)

    public class Entities {
    
        static class Entity{
            private String x;
            Entity( String x){
                this.x = x;
            }
            public String getX(){
                return x;
            }
        }
    
           public static Entity firstEntity() { 
               return new Entity("first Entity");
            }
           public static Entity secondEntity() {  
               return new Entity("second Entity");
            }
            public static Entity nthEntity() {
                return new Entity("nth Entity");}
    
            @FunctionalInterface interface  GetEntity{
                public Entity getEntity();
            }
    
            public static List<GetEntity> allEntities  = 
                 Arrays.asList(Entities::firstEntity, 
                               Entities::secondEntity,
                               Entities::nthEntity);
    
            public static void main(String ...p){
                allEntities
                    .stream()
                    .forEach(x->{System.out.println(x.getEntity().getX());});
            }
    }
    
  4. # 4 楼答案

    下面是调用EntitiesForTest类的指定方法并收集返回对象的samele代码:

    public static List<Entity> allEntities() {
        ArrayList<Entity> list = new ArrayList<Entity>();
        Method[] ma = EntitiesForTest.class.getMethods();
        Object[] emptyObject = new Object[0];
        for (int i = 0; i < ma.length; i++) {
            if (ma[i].getReturnType().equals(Entity.class) && 
                    ma[i].getParameterTypes().length == 0 && 
                    Modifier.isStatic(ma[i].getModifiers())) {
                try {
                    Entity e = (Entity)(ma[i].invoke(null, emptyObject));
                    list.add(e);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }