blob: 739d594818aa67a81fa84e473be4759032291e5e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package javassist.tools.reflect;
import java.lang.reflect.Method;
import java.util.Arrays;
import junit.framework.Assert;
/**
* Work with ClassMetaobjectTest.java
*
* @author Brett Randall
*/
public class Person {
public String name;
public static int birth = 3;
public static final String defaultName = "John";
public Person(String name, int birthYear) {
if (name == null)
this.name = defaultName;
else
this.name = name;
Person.birth = birthYear;
}
public String getName() {
return name;
}
public int getAge(int year) {
return year - birth;
}
public static void main(String[] args) throws Exception {
Person person = new Person("Bob", 10);
Metalevel metalevel = (Metalevel) person;
ClassMetaobject cmo = metalevel._getClass();
// this should return the index of the original getAge method
int methodIndex = cmo.getMethodIndex("getAge",
new Class[] {Integer.TYPE});
System.out.println(methodIndex);
// and the name verified by getMethodName
String methodName = cmo.getMethodName(methodIndex);
System.out.println(methodName);
// check the name
Assert.assertEquals("Incorrect method was found",
"getAge", methodName);
// check the arguments
Method method = cmo.getReflectiveMethods()[methodIndex];
Assert.assertTrue("Method signature did not match",
Arrays.equals(method.getParameterTypes(),
new Class[] {Integer.TYPE}));
System.out.println(method);
System.out.println("OK");
}
}
|