Java反射例子

package com.enorth.bean;

/**
* <p>Title: 学生 </p>
* <p>Description: 学生组件</p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: </p>
* @秦金雷
* @version 1.0
*/

public class Student {

private int studentId;
private String studentName;
private String studentSex;
private int studentAge;
private String studentAddress;

public int getStudentId() {
return studentId;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public String getStudentName() {
return studentName;
}

public void setStudentName(String studentName) {
this.studentName = studentName;
}

public String getStudentSex() {
return studentSex;
}

public void setStudentSex(String studentSex) {
this.studentSex = studentSex;
}

public int getStudentAge() {
return studentAge;
}

public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}

public String getStudentAddress() {
return studentAddress;
}

public void setStudentAddress(String studentAddress) {
this.studentAddress = studentAddress;
}

}

二 反射类

package com.enorth.reflection;

/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/

public class RefStudent {

public static Object loadClassObject(String className){

Object o = null;

try {

Class clas = Class.forName(className);

if(clas!=null){

try {
o = clas.newInstance();
}
catch (IllegalAccessException ex1) {
ex1.printStackTrace();
}
catch (InstantiationException ex1) {
ex1.printStackTrace();
}

}else
o = null;
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}

return o;
}
}

三 测试类

package com.enorth.test;

import com.enorth.reflection.RefStudent;
import com.enorth.bean.Student;

/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/

public class StudentTest {

/**
* 反射机制测试
*
* @param className String
*/
public static void testRef(String className){

Object o = RefStudent.loadClassObject(className);

if (o != null) {
Student student = (Student) o;
student.setStudentAddress("郑州市");
System.out.println(student.getStudentAddress());
}else {
System.out.println("反射机制获得的 Student 对象为空!");
}

}

/**
* main 方法测试
*
* @param args String[]
*/
public static void main(String[] args){
StudentTest.testRef("com.enorth.bean.Student");
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值