面試題-05

題目:

5、 定義一個標準的JavaBean,名叫Person,包含屬性name、age。使用反射的方式創建一個實例、調用構造函數初始化name、age,使用反射方式調用setName方法對名稱進行設置,不使用setAge方法直接使用反射方式對age賦值。

 

代碼:

 

package com.itheima;
/**
 * date :  Jun 14, 2013
 *
 * time :  7:51:47 PM
 *
 * author : Spole
 *
 */
public class Person {
 private String name;
 private int age;
 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 Person(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }
 public Person() {
  super();
 }
 @Override
 public String toString() {
  // TODO Auto-generated method stub
  return "Person-: Name:\t"+name+"\t Age:\t"+age;
 }
 
 

}

package com.itheima;

import java.lang.reflect.*;

import org.junit.Test;
/**
 * date :  Jun 14, 2013
 *
 * time :  7:49:19 PM
 *
 * author : Spole
 *
 */
/**
 * 題目:
 *
 * 定義一個標準的JavaBean,名叫Person,
 *
 * 包含屬性name、age。
 *
 * 使用反射的方式創建一個實例、
 *
 * 調用構造函數初始化name、age,
 *
 * 使用反射方式調用setName方法對名稱進行設置,
 *
 * 不使用setAge方法直接使用反射方式對age賦值。
 *
 */
public class Test05 {

 //調用構造函數初始化name、age
 @Test
 public void test51(){
  try {
   //加載類
   Class pclazz=Class .forName("com.itheima.Person");
   //加載構造方法
   Constructor c=pclazz.getConstructor(String.class,int.class);
   Person p=(Person) c.newInstance("SS",20);
      System.out.println(p);
  
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 
 /* 使用反射方式調用setName方法對名稱進行設置
  */
 @Test
 public void test52(){
  try {
   //加載類
   Class pclazz=Class .forName("com.itheima.Person");
   //加載構造方法
   Constructor c=pclazz.getConstructor();
   Person p=(Person) c.newInstance(null);
   Method method = pclazz.getMethod("setName", String.class); 
   method.invoke(p, "QQQQQQQ");
   System.out.println(p);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 /* 
  *  不使用setAge方法直接使用反射方式對age賦值。
  */
 @Test
 public void test53(){
  try {
   //加載類
   Class pclazz=Class .forName("com.itheima.Person");
   //加載構造方法
   Constructor c=pclazz.getConstructor();
   Person p=(Person) c.newInstance(null);
   //得到想操作的字段
   Field a = pclazz.getDeclaredField("age");
   //允許反射私有方法。。
   a.setAccessible(true);
   //獲取字段類型。。
   Class type = a.getType();
   if(type.equals(int.class)){
    //設置字段值
    a.set(p, 20);
   }
   System.out.println(p);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章