反射:在程序的運行過程中,能夠探測類所擁有的屬性和行為的一種能力,把這種機制成為反射.
反射的使用場景:
1>把字符串轉(zhuǎn)換成類對象
2>做通用代碼(框架)
Java反射相關(guān)操作如下:
a.獲取成員方法Method
b.獲取成員變量Field
c.獲取構(gòu)造函數(shù)Constructor
例如:
package reflectDemo;
public class Student
{
private String name;
private int age;
private String msg = "hello test";
public void tell()
{
System.out.println(msg);
}
public void fun(String name, int age)
{
System.out.println("我叫" + name + ",今年" + age + "歲");
}
}
package reflectDemo;
import java.lang.reflect.Method;
public class ReflectTest
{
public static void main(String[] args) throws Exception
{
// 獲取類對象
Class c = Class.forName("reflectDemo.Student");
// 創(chuàng)建類對象的實例
Object object = c.newInstance();
Method method2 = c.getMethod("fun", String.class, int.class);
method2.invoke(object, "dog", 2);
Method method = c.getMethod("tell");
method.invoke(object);
}
}
結(jié)果:
我叫dog,今年2歲
hello test