本文主要對java反射的簡單應用,獲取字節碼,類的字段、方法,調用方法等!掌握基礎,日後可以舉一反三!
效果展示:
源碼:
/**
* 反射的簡單運用
* @author Smilexs
*/
public class TestReflect {
public static void main(String[] args) throws Exception{
/**1、獲取類的字節碼*/
Class c = Class.forName("com.itheima.Person");
/**2、通過構造器獲取實例*/
System.out.println("---------------實例內容---------------");
Constructor con = c.getConstructor(String.class,int.class,boolean.class);
Person p = (Person)con.newInstance(new Object[]{"小裏",18,true});
System.out.println("姓名:"+p.getName()+"\t年齡:"+p.getAge()+"\t性別:"+(p.isSex()==true?"男":"女"));
/**3、輸出所有字段*/
System.out.println("---------------字段名---------------");
Field[] fields = c.getDeclaredFields();//可以返回私有字段
for (Field field : fields) {
System.out.println(field.getName());
}
/**4、輸出所有方法*/
System.out.println("---------------方法名---------------");
// Method[] methods = c.getMethods();//不會輸出私有方法名
Method[] methods = c.getDeclaredMethods();//輸出所有申明的方法
for (Method method : methods) {
System.out.println(method.getName()+"()");
}
/**5、調用方法*/
System.out.println("---------------調用方法內容---------------");
for (Method method : methods) {
if(method.getName()=="print"){
method.setAccessible(true);//設置可以訪問私有方法,暴力反射
System.out.println(method.invoke(p, "hello world!"));
}
}
}
}
/**
* 個人信息
*/
public class Person {
public String name ;
private int age;
private boolean sex;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String name, int age, boolean sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
private String print(String content){
return "顯示內容爲:"+content;
}
}