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();
}
}
}
