在Java中,调用类的方法有两种方式:对于静态方法可以直接使用类名调用,对于非静态方法必须使用类的对象调用。反射机制提供了比较另类的调用方式,可以根据需要指定要调用的方法,而不必在编程时确定。调用的方法不仅限于public的,还可以是private的。编写程序,使用反射机制调用Math类的静态方法sin()和非静态方法equals()。
思路如下:使用Math.class.getDeclaredMethod("sin", Double.TYPE);访问指定的方法,其中”sin”表示要访问的方法的名称为sin,Double.TYPE表示入口参数的类型为double。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
import java.lang.reflect.Method; public class DongTai { public
static void main(String[] args) { try
{ System.out.println( "调用Math类的静态方法sin()" ); Method sin = Math. class .getDeclaredMethod( "sin" , Double.TYPE); Double sin1 = (Double) sin.invoke( null , new
Integer( 1 )); System.out.println( "1的正弦值是:"
+ sin1); System.out.println( "调用String类的非静态方法equals()" ); Method equals = String. class .getDeclaredMethod( "equals" , Object. class ); Boolean mrsoft = (Boolean) equals.invoke( new
String( "明日科技" ), "明日科技" ); System.out.println( "字符串是否是明日科技:"
+ mrsoft); } catch
(Exception e) { e.printStackTrace(); } } } |
效果如图:
原文:http://www.cnblogs.com/cysolo/p/3561567.html