How do I invoke a Java method when given the method name as a string?

前端 未结 21 2092
耶瑟儿~
耶瑟儿~ 2020-11-21 04:50

If I have two variables:

Object obj;
String methodName = \"getName\";

Without knowing the class of obj, how can I call the met

21条回答
  •  抹茶落季
    2020-11-21 05:18

    Student.java

    class Student{
        int rollno;
        String name;
    
        void m1(int x,int y){
            System.out.println("add is" +(x+y));
        }
    
        private void m3(String name){
            this.name=name;
            System.out.println("danger yappa:"+name);
        }
        void m4(){
            System.out.println("This is m4");
        }
    }
    

    StudentTest.java

    import java.lang.reflect.Method;
    public class StudentTest{
    
         public static void main(String[] args){
    
            try{
    
                Class cls=Student.class;
    
                Student s=(Student)cls.newInstance();
    
    
                String x="kichha";
                Method mm3=cls.getDeclaredMethod("m3",String.class);
                mm3.setAccessible(true);
                mm3.invoke(s,x);
    
                Method mm1=cls.getDeclaredMethod("m1",int.class,int.class);
                mm1.invoke(s,10,20);
    
            }
            catch(Exception e){
                e.printStackTrace();
            }
         }
    }
    

提交回复
热议问题