反射









package com.lovo.application;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


import javax.swing.JOptionPane;


import com.lovo.bean.RoomBean;


public class TestApplication {

public static void print(Object obj, String className, String fieldName){
try {
Class objClass = Class.forName(className);
char[] nameChar = fieldName.toCharArray();
if(nameChar[0] >= 'a' && nameChar[0] <= 'z'){
nameChar[0] -= 32;
}
String methodName = "get" + new String(nameChar);
Method method = objClass.getMethod(methodName);
Object value = method.invoke(obj);

JOptionPane.showMessageDialog(null, "对象身上的" + fieldName + "属性的值是:" + value);

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}









package com.lovo.bean;


public class RoomBean {

private int roomId;

private String address;

private String hostName;

public RoomBean(){

}



public RoomBean(int roomId, String address, String hostName) {
super();
this.roomId = roomId;
this.address = address;
this.hostName = hostName;
}






public int getRoomId() {
return roomId;
}


public void setRoomId(int roomId) {
this.roomId = roomId;
}


public String getAddress() {
return address;
}


public void setAddress(String address) {
this.address = address;
}


public String getHostName() {
return hostName;
}


public void setHostName(String hostName) {
this.hostName = hostName;
}
}








package com.lovo.bean;


import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;


public final class StudentBean implements Serializable,Runnable{

public int stuId;

String stuName;

protected boolean stuGender;

public StudentBean(){

}


public StudentBean(String stuName, boolean stuGender) {
super();
System.out.println("带两个参数的构造");
this.stuName = stuName;
this.stuGender = stuGender;
}


private StudentBean(int stuId, String stuName, boolean stuGender) {
super();
this.stuId = stuId;
this.stuName = stuName;
this.stuGender = stuGender;
}


public int getStuId() {
return stuId;
}


public void setStuId(int stuId) {
this.stuId = stuId;
}


public String getStuName() {
return stuName;
}


public void setStuName(String stuName) {
this.stuName = stuName;
}


public boolean isStuGender() {
return stuGender;
}


public void setStuGender(boolean stuGender) {
this.stuGender = stuGender;
}


public void study(int time,String lesson) throws IOException,SQLException{
System.out.println(this.stuName + "花了" + time + "个小时,学习" + lesson + "。");
}


public void run() {
// TODO Auto-generated method stub

}

}







package com.lovo.test;


import com.lovo.application.TestApplication;
import com.lovo.bean.StudentBean;


public class TestMain {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

// com.lovo.bean.StudentBean stu = new com.lovo.bean.StudentBean("li4",false);
StudentBean stu = new StudentBean("w", false);
TestApplication.print(stu, "com.lovo.bean.StudentBean", "stuName");

}

// public static void test(int[] array){
//
// }

public static void test(int... array){

}


}










package com.lovo.test;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;


import javax.swing.JOptionPane;


import com.lovo.bean.StudentBean;


public class TestReflect {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 1、获取类的Class对象
*/
//1-1、根据类型名获取Class对象--所有类型(包括:基本、类、接口、数组和void)都可以通过这种方式获得它的Class对象
Class stuClass = StudentBean.class;
Class strClass = String.class;
Class arrayClass = int[].class;
Class voidClass = void.class;
Class intClass = int.class;//JDK1.5以后才能用,之前要用包装类.TYPE

//1-2、根据实例对象 获取 该实例所属类的Class对象--引用数据类型可以通过这种方式获得它的Class对象
StudentBean zhang3 = new StudentBean("zhang3",true);
Class stuClass2 = zhang3.getClass();
Class strClass2 = "hello".getClass();
Class arrayClass2 = new int[10].getClass();

//1-3、根据类的字符串全名(类限定名)获取该类的Class对象
//特点:1、唯一的一种动态获取Class对象的方式,只有它能达到编译时未知,运行时探究的效果;
//    2、Class.forName()不仅仅获取已经加载的类的Class对象这么简单;如果传入的类没有被加载,它
//      还可以让JVM对这个类进行加载产生Class对象.
//结论:这种方式是现实开发中使用反射,最常用的API
// try {
// String className = JOptionPane.showInputDialog("请输入你要获取的Class对象的类名");
// Class stuClass3 = Class.forName(className);
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }

/**
* 2、通过Class对象,探究类的信息
*/

//2-1、探究类的申明部分信息--无需掌握
String packageName = stuClass.getPackage().getName();//得到包的名称
String className = stuClass.getName();//得到类全名
String classSimpleName = stuClass.getSimpleName();//得到类的简单名
String parentClassName = stuClass.getSuperclass().getSimpleName();//得到父类
Class[] interClasses = stuClass.getInterfaces();//得到实现的接口的Class对象
String allInterNames = "";
for(int i = 0; i < interClasses.length; i++){
allInterNames += interClasses[i].getSimpleName();
if(i != interClasses.length - 1){
allInterNames += ",";
}
}

int classMod = stuClass.getModifiers();//得到类的修饰符
String classModStr = Modifier.toString(classMod);

System.out.println("package " + packageName + ";");
System.out.println(classModStr + " class " + classSimpleName + " extends " + parentClassName + 
" implements " + allInterNames + "{");
//2-2、探究类的属性---Field
Field[] allPublicFields = stuClass.getFields();//得到所有的公共属性
Field[] allFields = stuClass.getDeclaredFields();//得到所有被申明的属性
try {
Field thePublicField = stuClass.getField("stuId");//根据属性名得到指定的公共属性
Field theField = stuClass.getDeclaredField("stuGender");//根据属性名得到指定的被申明的属性
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

for(Field tmpF : allFields){
String typeName = tmpF.getType().getSimpleName();//得到属性的类型
String fieldName = tmpF.getName();//得到属性的名字
String fieldModStr = Modifier.toString(tmpF.getModifiers());//得到属性的修饰符
System.out.println("\t" + fieldModStr + " " + typeName + " "  + fieldName + ";");
System.out.println();
}


//2-3、探究类的构造---Constructor
Constructor[] allPublicCons = stuClass.getConstructors();//得到所有的公共构造方法
Constructor[] allCons = stuClass.getDeclaredConstructors();//得到所有申明的构造方法
try {
Constructor thePublicCons = stuClass.getConstructor(String.class,boolean.class);//得到指定的公共构造方法
Constructor theCons = stuClass.getDeclaredConstructor();//得到指定的被申明的构造方法
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

for(Constructor conTmp : allCons){
String conModStr = Modifier.toString(conTmp.getModifiers());//得到构造方法的修饰符
String conName = conTmp.getName();//得到构造方法的名字(隐藏知识点:构造方法真正的名字就是类限定名)
Class[] paramTypes = conTmp.getParameterTypes();//得到构造方法的形参列表
String paramsStr = "";
if(paramTypes != null && paramTypes.length != 0){
for(int i = 0; i < paramTypes.length; i++){
paramsStr += paramTypes[i].getSimpleName();
if(i != paramTypes.length - 1){
paramsStr += ",";
}
}
}


System.out.println("\t" + conModStr + " " + conName + "(" + paramsStr + ")");
System.out.println();
System.out.println();
}


//2-4、探究类的方法---Method
Method[] allPublicMethods = stuClass.getMethods();//得到所有的公共方法
Method[] allMethods = stuClass.getDeclaredMethods();//得到所有申明的方法
try {
Method thePublicMethod = stuClass.getMethod("run");//得到指定的公共方法
Method theMethod = stuClass.getDeclaredMethod("study", int.class,String.class);//得到指定的被申明的方法
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

for(Method method : allMethods){
String methodMod = Modifier.toString(method.getModifiers());//得到方法的修饰符
String methodReturn = method.getReturnType().getSimpleName();//得到方法的返回类型名
String methodName = method.getName();//得到方法的名字
String methodParamStr = "";
Class[] params = method.getParameterTypes();//得到方法的形参
if(params != null && params.length != 0){
for(int i = 0; i < params.length; i++){
methodParamStr += params[i].getSimpleName();
if(i != params.length - 1){
methodParamStr += ",";
}
}
}
String methodThrows = "";
Class[] exceptions = method.getExceptionTypes();//得到方法抛出的异常
if(exceptions != null && exceptions.length != 0){
methodThrows += "throws ";
for(int i = 0; i < exceptions.length; i++){
methodThrows += exceptions[i].getSimpleName();
if(i != exceptions.length - 1){
methodThrows += ",";
}
}


}

System.out.println("\t" + methodMod + " " + methodReturn + " " + 
methodName + "(" + methodParamStr + ")" + methodThrows);
}

System.out.println("}");


/**
* 3、操作探究到的信息
*/

//3-1、产生实例对象
//3-1-1、直接利用Class对象产生实例对象(必须要有公共无参构造)
try {
StudentBean stu = (StudentBean)stuClass.newInstance();
System.out.println(stu);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3-1-2、通过调用Contructor对象的方法,产生实例对象--受访问修饰符的限制
try {
Constructor con = stuClass.getDeclaredConstructor(String.class,boolean.class);
StudentBean stu = (StudentBean)con.newInstance("wang5",true);
System.out.println(stu.getStuName());

} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//3-2、探究到Field对象,就可以对属性进行赋值取值
try {
Field idField = stuClass.getDeclaredField("stuId");
idField.setAccessible(true);//破坏封装,不准用!!!
idField.set(zhang3, 10);
System.out.println(zhang3.getStuId());
System.out.println(idField.get(zhang3));
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//3-3、探究到Method对象,调用方法
try {
Method theMethod = stuClass.getDeclaredMethod("study", int.class,String.class);
theMethod.invoke(zhang3, 5,"java");
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值