简体   繁体   English

如何在具有相同类型参数的Java中创建方法?

[英]How Can I Create method In Java With Same Type Parameter?

My code looks like below: 我的代码如下所示:

enum EnumType {
 CATEGORY,
 GROUP,
 MAIN
}

Methods: 方法:

public void call(EnumType type){
   switch(type):
     case CATEGORY:
        return methodForCategory();
     case GROUP:
        return methodForGroup();
     ...
}
public void methodForCategory(){
   ... Operations according to EnumType.CATEGORY
}
public void methodForGroup(){
   ... Operations according to EnumType.GROUP
}
public void methodForMain(){
   ... Operations according to EnumType.MAIN
}

But I want to call it without switch/case like below; 但是我想在没有开关/情况下调用它,如下所示;

public void call(EnumType type){
    methodForType(EnumType type);
}

Is it possible or is there any better alternative? 有可能还是有更好的选择?

You can create the method implementation inside the enum as below: 您可以在枚举内创建方法实现,如下所示:

public enum EnumType {

  CATEGORY {

    @Override
    public void processMethod() {
      // Do something here
    }

  },
GROUP {

    @Override
    public void processMethod() {
      // Do something here
    }

  },
MAIN {

    @Override
    public void processMethod() {
      // Do something here
    }

  };

public abstract void processMethod();
}

And update call method implementation as: 并将调用方法实现更新为:

public void call(EnumType type){
   type.processMethod();
}

And switch code should not return anything as method return type is void . 并且切换代码不应返回任何内容,因为方法的返回类型为void

You can use an EnumMap as a registry of methods and using the Enum supplied you can return the correct implementation of the Runnable . 您可以将EnumMap用作方法的注册表,并使用提供的Enum可以返回Runnable的正确实现。 I have used Runnable as a functional interface as it takes no inputs and produces no output. 我已经将Runnable用作功能接口,因为它不输入也不产生任何输出。

In another class where you have the business logic, you can initialize the map and add the corresponding Runnable implementation: 在具有业务逻辑的另一个类中,可以初始化map并添加相应的Runnable实现:

class Strategy{

    private final EnumMap<EnumType, Runnable> map;

    public Strategy(){
        //Initialize values here
        map = new EnumMap<>(EnumType.class);
        map.put(EnumType.CATEGORY, () -> {
            System.out.println("CATEGORY");
        });
        map.put(EnumType.GROUP, () -> {
            System.out.println("GROUP");
        });
        map.put(EnumType.MAIN, () -> {
            System.out.println("MAIN");
        });
    }

    public void call(EnumType type){
        map.get(type).run();
    }
}

Then you can invoke the call() method by supplying the type of Enum as a parameter: 然后,您可以通过提供Enum类型作为参数来调用call()方法:

public static void main(String args[]){
    Strategy str = new Strategy();
    str.call(EnumType.CATEGORY);
    str.call(EnumType.GROUP);
    str.call(EnumType.MAIN);
}

You can use a variant of the Command design pattern and store a reference to a function as a field of the enumerated type, and provide a common execute() method to execute the custom operation. 您可以使用Command设计模式的变体,并将对函数的引用存储为枚举类型的字段,并提供通用的execute()方法来执行自定义操作。

enum EnumType {
    CATEGORY( ()-> {} ), 
    GROUP( ()-> {System.out.println("Hello");} ),
    MAIN( EnumType::doSomething );

    private final Runnable operation;

    private EnumType(Runnable operation) {
        this.operation = operation;
    }

    public void execute() {
        operation.run();
    }

    private static final void doSomething() {
        System.out.println("World");
    }
}

If the methods are short, you can use lambda expression (as for GROUP ). 如果方法很短,则可以使用lambda表达式(对于GROUP )。 If they are longer, you can use method references (as for MAIN ). 如果它们更长,则可以使用方法引用(与MAIN )。 If you need arguments or a return value, you can use a different functional interface . 如果需要参数或返回值,则可以使用其他功能接口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在方法中创建与ArrayList参数相同类型的ArrayList - Create same type ArrayList as ArrayList parameter in method 如何为参数列表和/或返回类型中的“任何映射条目”值创建通用方法签名? - How can I create a generic method signature for “any map entry” value in the parameter list and/or return type? 为什么我不能在Java中创建类型参数的数组? - Why can't I create an array of a type parameter in Java? Java 在接口中创建方法并更改参数类型 - Java create method in Interface and change the parameter type Java - 如何将方法的返回类型作为参数传递? - Java - How do I pass the return type of a method as parameter? Java 8:如何将静态方法用作另一个方法的参数? - Java 8: How can I use a static method as a parameter for another method? 我如何在 Java 中创建通用方法? - How i can create Generic Method in Java? 我可以指定方法参数中的多个泛型必须使用“ <? extends Type> ”? - Can I specify that multiple generics in a method parameter must be the same type using “<? extends Type>”? Java:如何强制 class 类型参数与泛型方法中指定的泛型类型相同? - Java: How do you enforce a class type parameter to be the same as generic type specified in a generic method? JAva:如何将自定义对象类型作为参数传递给方法,并返回相同的自定义对象类型值 - JAva:How to pass a custom object type as a parameter to a method and return the same custom object type value back
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM