10 System.out.println(obj);
11 }
12 /* 输出结果如下:
13 java.awt.Point[x=123,y=123]
14 */
2) 通过域方法的名称和参数列表签名获取并执行该方法(静态方法):
1 public static void main(String args[]) throws Exception {
2 //通过方法名称和参数列表签名获取类的静态域方法。
3 Method m = Math.class.getMethod("sqrt", new Class[] { double.class });
4 //由于是静态方法,第一个参数传null,如是是非静态函数,可以
5 //该参数看成this引用,传递对象即可,后面的参数列表表示该
6 //反射方法的参数列表。这里Math.sqrt只有一个double类型的
7 //参数。invoke的返回值只能是Object类型,因此也只能先将其
8 //转换为原始类型的包装类型,在从包装类型获取原始类型。
9 Double o = (Double)m.invoke(null, 10);
10 System.out.println(o.doubleva lue());
11 }
12 /* 输出结果如下:
13 3.1622776601683795
14 */
3) 通过域方法的名称和参数列表签名获取并执行该方法(非静态方法):
1 public class MyTest {
2 public static void main(String args[]) throws Exception {
3 String firstWord = "Hello ";
4 String secondWord = "everybody.";
5 String bothWords = append(firstWord, secondWord);
6 System.out.println(bothWords);
7 }
8
9 public static String append(String firstWord, String secondWord) {
10 String result = null;
11 Class
12 //初始化域方法的参数类型列表
13 Class< >[] parameterTypes = new Class[] { String.class };
14 Method concatMethod;
15 //初始化域方法的参数
16 Object[] arguments = new Object[] { secondWord };
17 try {
18 //根据域方法的名称和参数列表获取域方法的反射对象
19 concatMethod = c.getMethod("concat", parameterTypes);
20 //和静态方法的反射调用不同,这里的第一个参数必须填入,其作用
21 //相当于firstWord.concat(secondword);
22 result = (String) concatMethod.invoke(firstWord, arguments);
23 } catch (NoSuchMethodException e) {
24 System.out.println(e);
25 } catch (IllegalAccessException e) {
26 System.out.println(e);
27 } catch (InvocationTargetException e) {
28 System.out.println(e);
29 }
30 return result;
31 }
32 }
33 /* 输出结果如下:
34 Hello everybody.
35 */
4) 通过反射调用对象的私有域方法:
1 public class MyTest {
2 public static void main(String args[]) throws Exception {
3 TestClass tc = new TestClass();
4 Class< > c = tc.getClass();
5 Method m = c.getDeclaredMethod("m");
6 //必须调用该方法通过反射的方法设置这个private的可访问性
7 //为true,否则调用时将会抛出IllegalAccessException异常
8 m.setAccessible(true);
9 Object o = m.invoke(tc);
10 }
11 }
12 class TestClass {
13 private void m() {
14 System.out.println("This is private method TestClass.m().");
15 }
16 }
17 /* 输出结果如下:
18 This is private method TestClass.m().
19 */
5) 通过栈帧获取当前方法的名称:
1 public static void main(String args[]) throws Exception {
2 System.out.println(new Exception().getStackTrace()[0].getMethodName());
3
4 //这里的第0帧为getStackTrace()
5 System.ou