一个xx.java 这里有很多方法,我想利用我传进去的值(值和方法名相同)去调用,怎么做?

2026年09月24日 19:32
有2个网友回答
网友(1):

public class er {

    public er(String args) {
        if (args.equalsIgnoreCase("show")) {
            er.show();
        }
        if (args.equalsIgnoreCase("print")) {
            er.print();
            
        }
        
    }

    public static void main(String[] args) {
        String str = args[0];
        er e=new er(args[1]);
        System.out.println("str="+str);
        

    }

    private static void show() {
        System.out.println("show方法");
        
    }

    private static void print() {
        System.out.println("print show方法");
        
    }

}

网友(2):

原理: javaf反射机制进行调用

参考代码

import java.lang.reflect.Method;

public class TestRef {//测试类

public static void main(String args[]) throws Exception {
String method = "outInfo";//方法名
String name = "张三";//方法参数

Foo foo = new Foo();
Class clazz = foo.getClass();
Method m1 = clazz.getDeclaredMethod(method, String.class);
m1.invoke(foo, name);
}
}

class Foo { 
public void outInfo(String name) {
System.out.println("hello " + name);
}
}

拓展,可以百度搜索 java反射机制