java通过getMethod动态调用类的方法
一般调用方法的时候我们需要new一个对象,然后通过这个对象直接打点去调用他的方法。
public class MyTest {
public void sayHello ( ) {
System. out. println ( "哈喽,我是小新!" ) ;
}
public static void main ( String[ ] args) throws Exception{
MyTest t = new MyTest ( ) ;
t. sayHello ( ) ;
}
}
但是有时候我们不确定需要具体调用哪个方法,需要根据业务动态的调用,那么就需要用到这个类的getMethod方法了。我们修改实现代码如下:
public class MyTest {
public void doMethod ( String methodName) throws Exception {
this . getClass ( ) . getMethod ( methodName, new Class [ ] { } ) . invoke ( this , new Object [ ] { } ) ;
}
public void sayHello ( ) {
System. out. println ( "哈喽,我是小新!" ) ;
}
public static void main ( String[ ] args) throws Exception {
MyTest t = new MyTest ( ) ;
t. doMethod ( "sayHello" ) ;
}
}
以上就是简单的动态调用方法了。如果动态调用的方法有返回值,怎么办呢?
public class MyTest {
public Object doMethod ( String methodName) throws Exception {
return this . getClass ( ) . getMethod ( methodName, new Class [ ] { } ) . invoke ( this , new Object [ ] { } ) ;
}
public String sayHello ( ) {
System. out. println ( "哈喽,我是小新!" ) ;
return "小新" ;
}
public static void main ( String[ ] args) throws Exception {
MyTest t = new MyTest ( ) ;
Object resoOj = t. doMethod ( "sayHello" ) ;
System. out. println ( resoOj) ;
}
}
为什么返回的是object呢?因为getMethod这个方法不知道你的方法返回的具体是什么类型的,只能返通用的Object型
还有如果我需要传参数进方法呢?具体代码如下
以上就是大多数情况下的动态调用方法了,记录一下