Java中无需条件语句/反射等,根据命令行输入调用对应方法的方案咨询
Hey there! Let's work through this problem together. Since you're restricted from using conditionals, loops, or reflection, we can leverage direct value-to-action mapping using Java's functional interfaces and collections. Here's a clean, maintainable approach:
Step 1: Define a Functional Interface
First, create a functional interface to standardize the signature of your target methods. This lets us treat each method as a reusable "action" object:
@FunctionalInterface interface InputAction { void run(); // Adjust the method signature if your methods take parameters/return values }
Step 2: Map Inputs to Corresponding Methods
Use a Map to bind your input strings ("A", "B", "C") directly to their respective method references. This eliminates any need for conditional checks:
// Initialize the map once (e.g., in your class constructor or static block) Map<String, InputAction> actionMap = new HashMap<>(); actionMap.put("A", this::handleInputA); // Replace with your actual method name actionMap.put("B", this::handleInputB); actionMap.put("C", this::handleInputC);
Step 3: Execute the Action from Command Line Input
Grab your command line argument, fetch the corresponding action from the map, and run it:
public static void main(String[] args) { // Optional: Handle missing input with a default action (no conditionals needed) String input = args.length > 0 ? args[0] : ""; actionMap.getOrDefault(input, () -> System.err.println("No valid input provided")).run(); }
Bonus: Type-Safe Alternative with Enum
For even stricter type safety, you can use an enum to encapsulate inputs and their actions. This avoids string-based key errors entirely:
enum InputType { A("A", YourClass::handleInputA), B("B", YourClass::handleInputB), C("C", YourClass::handleInputC); private final String inputValue; private final InputAction action; InputType(String inputValue, InputAction action) { this.inputValue = inputValue; this.action = action; } // Precompute a lookup map for fast access private static final Map<String, InputType> INPUT_MAP = Arrays.stream(values()) .collect(Collectors.toMap(InputType::getInputValue, Function.identity())); public static InputType fromInput(String input) { return INPUT_MAP.get(input); } public void executeAction() { action.run(); } public String getInputValue() { return inputValue; } }
Then use it like this:
InputType.fromInput(args[0]).executeAction();
Both approaches work entirely without if, switch, loops, or reflection—they rely on pre-built mappings to directly trigger the correct method based on input.
内容的提问来源于stack exchange,提问作者javalearner

