1
package
com.pplk.reflect;
2
3
import
java.lang.reflect.Constructor;
4
import
java.lang.reflect.Method;
5
6
public
class
TestReflect
{
7
8
9
public
TestReflect()
{}
10
11
public
void
findMeth()
{
12
try
{
13
Class cls
=
Class.forName(
"
com.pplk.reflect.TestReflect
"
);
14
Class []par
=
new
Class[
2
];
15
//
The Class instance representing the primitive type int.
16
par[
0
]
=
Integer.TYPE;
17
par[
1
]
=
Integer.TYPE;
18
Method meth
=
cls.getMethod(
"
add
"
, par);
19
//
find
20
//
*******************************************
//
21
//
run
22
TestReflect te
=
new
TestReflect();
23
Object []obj
=
new
Object[
2
];
24
obj[
0
]
=
new
Integer(
50
);
25
obj[
1
]
=
new
Integer(
55
);
26
27
//
Invokes the underlying method represented by this Method object,
28
//
on the specified object with the specified parameters
29
Object o
=
meth.invoke(te, obj);
30
Integer inte
=
(Integer)o;
31
System.out.println(inte.intValue() );
32
}
catch
(Throwable e)
{ System.err.println(e); }
33
}
34
35
36
public
void
getMeth(String string)
{
37
try
{
38
Class cls
=
Class.forName(string);
39
//
Method []me = cls.getDeclaredMethods();
40
Constructor []me
=
cls.getDeclaredConstructors();
41
for
(
int
i
=
0
; i
<
me.length; i
++
)
{
42
//
Method m = me[i];
43
Constructor m
=
me[i];
44
System.out.println(
"
name =
"
+
m.getName() );
45
System.out.println(
"
decl class =
"
+
m.getDeclaringClass() );
46
47
Class []para
=
m.getParameterTypes();
48
for
(
int
j
=
0
; j
<
para.length; j
++
)
{
49
System.out.println(
"
para#
"
+
j
+
"
"
+
para[j]);
50
}
51
52
Class []exce
=
m.getExceptionTypes();
53
for
(
int
k
=
0
; k
<
exce.length; k
++
)
{
54
System.out.println(
"
exce#
"
+
k
+
"
"
+
exce[k]);
55
}
56
57
//
System.out.println("return type = " + m.getReturnType() );
58
System.out.println(
"
-----------------------------------
"
);
59
}
60
}
catch
(Exception e)
{ e.printStackTrace(); }
61
}
62
63
/** */
/**
64
*/
65
public
int
add(
int
a,
int
b)
{
66
return
a
*
b;
67
}
68
69
/** */
/**
70
*/
71
public
void
instanceRunTime()
{
72
try
{
73
Class cls
=
Class.forName(
"
com.pplk.reflect.TestReflect
"
);
74
Class []par
=
{java.lang.String.
class
}
;
75
Constructor ct
=
cls.getConstructor(par);
76
77
Object []arg
=
{
"
instanceRunTime
"
}
;
78
Object obj
=
ct.newInstance(arg);
79
}
catch
(Throwable e)
{ System.err.println(e); }
80
}
81
82
/** */
/**
83
*/
84
public
static
void
main(String[] args)
{
85
TestReflect test
=
new
TestReflect();
86
//
display information about class' s constructors and methods
87
test.getMeth(
"
java.lang.String
"
);
88
System.out.println(
"
\n
"
+
"
------------------
"
+
"
\n
"
+
"
findMethod()
"
);
89
test.findMeth();
90
System.out.println(
"
\n
"
+
"
------------------
"
+
"
\n
"
+
"
instanceRT()
"
);
91
test.instanceRunTime();
92
}
93
94
}
95