你最愿意做的哪件事,才是你的天赋所在

0%

java学习之路4-反射机制

java反射机制

这是一点与c++不同的地方,java有一个所有类的超类,也就是Object,不论是系统自带类,或者你自己写的,都是这个类的子类。
还有一个类Class,这个类跟反射机制息息相关。

反射机制作用

1.在运行时判断任意一个对象所属的类;
2.在运行时构造任意一个类的对象;
3.在运行时判断任意一个类所具有的成员变量和方法;
4.在运行时调用任意一个对象的方法;生成动态代理。
第一点,可以获得当前对象是什么类
第二点,既然知道是什么类了,那么我就可以自己构造一个实例对象
第三点,我知道你是什么类了,就可以找到你的成员以及方法。
第四点,我不仅知道你的方法,我还能够用你的方法

代码实现

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
package reflect;
import java.lang.reflect.*;
public class reflectTest {
public static void main(String[] args) throws Exception
{
Employee q = new Employee("111",15);
Class c1 = q.getClass();
//获取类名
System.out.println(c1.getName());
//获取所有公共构造方法
Constructor[] s =c1.getConstructors();
for(Constructor k:s)
{
System.out.println(k);
}
Method square = reflectTest.class.getMethod("square", double.class);
//获取自定义函数的方法
Method sqrt = Math.class.getMethod("sqrt", double.class);
//获取Math的方法
printTable(1,10,10,square);
//使用方法
printTable(1,10,10,sqrt);
}
public static void printTable(double from,double to,int n,Method f)
{ System.out.println(f);
double dx = (to-from)/(n-1);
for(double x=from;x<=to;x+=dx)
{
try {
double y =(Double)f.invoke(null, x);
//使用时,若不符合该方法的操作则会发出异常
System.out.printf("%10.4f | %10.4f\n",x,y);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//这句话的意思时打印异常错误的情况
}
}
}
public static double square(double x) {
return x*x;
}
}

输出

reflect.Employee
public reflect.Employee(java.lang.String,int)
public reflect.Employee()
public static double reflect.reflectTest.square(double)
1.0000 | 1.0000
2.0000 | 4.0000
3.0000 | 9.0000
4.0000 | 16.0000
5.0000 | 25.0000
6.0000 | 36.0000
7.0000 | 49.0000
8.0000 | 64.0000
9.0000 | 81.0000
10.0000 | 100.0000
public static double java.lang.Math.sqrt(double)
1.0000 | 1.0000
2.0000 | 1.4142
3.0000 | 1.7321
4.0000 | 2.0000
5.0000 | 2.2361
6.0000 | 2.4495
7.0000 | 2.6458
8.0000 | 2.8284
9.0000 | 3.0000
10.0000 | 3.1623

你最愿意做的哪件事,才是你的天赋所在
-------------你最愿意做的哪件事才是你的天赋所在-------------