public
class
Calculator{
public
double
add(
double
score1,
double
score2){
return
score1 + score2;
}
public
void
print(){
System.out.println(
"OK"
);
}
public
static
double
mul(
double
score1,
double
score2){
return
score1 * score2;
}
}
|
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
|
public
class
CalculatorTest {
public
static
void
main(String[] args)
throws
Exception {
//通过类的.class属性获取
Class<Calculator> clz = Calculator.
class
;
//或者通过类的完整路径获取,这个方法由于不能确定传入的路径是否正确,这个方法会抛ClassNotFoundException
// Class<Calculator> clz = Class.forName("test.Calculator");
//或者new一个实例,然后通过实例的getClass()方法获取
// Calculator s = new Calculator();
// Class<Calculator> clz = s.getClass();
//1. 获取类中带有方法签名的mul方法,getMethod第一个参数为方法名,第二个参数为mul的参数类型数组
Method method = clz.getMethod(
"mul"
,
new
Class[]{
double
.
class
,
double
.
class
});
//invoke 方法的第一个参数是被调用的对象,这里是静态方法故为null,第二个参数为给将被调用的方法传入的参数
Object result = method.invoke(
null
,
new
Object[]{
2.0
,
2.5
});
//如果方法mul是私有的private方法,按照上面的方法去调用则会产生异常NoSuchMethodException,这时必须改变其访问属性
//method.setAccessible(true);//私有的方法通过发射可以修改其访问权限
System.out.println(result);
//结果为5.0
//2. 获取类中的非静态方法
Method method_2 = clz.getMethod(
"add"
,
new
Class[]{
double
.
class
,
double
.
class
});
//这是实例方法必须在一个对象上执行
Object result_2 = method_2.invoke(
new
Calculator(),
new
Object[]{
2.0
,
2.5
});
System.out.println(result_2);
//4.5
//3. 获取没有方法签名的方法print
Method method_3 = clz.getMethod(
"print"
,
new
Class[]{});
Object result_3 = method_3.invoke(
new
Calculator(),
null
);
//result_3为null,该方法不返回结果
}
}
|
package thread;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Teacher {
public String getName(String name, String address, Integer age) {
return name + "是一名人民教师,在"+address+","+age+"岁";
}
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("thread.Teacher");
Method method = clazz.getMethod("getName", String.class, String.class, Integer.class);
Object obj = method.invoke(clazz.newInstance(), "李梅","上海", 21);
System.out.println(obj);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}