非常好用的JAVA动态类处理源码

自己有空对JAVA动态类进行番研究,开发了这个动态类处理的类,里面包含的功能有:动态运行类的方法(可传参数),动态设置、提取类属性,动态将结果集(Resultset)赋值到PO对象、PO对象向量表等实用的方法,如果这些功能对您有帮助,或您有什么更好的想法与相关源码,欢迎交流。

 

以下为原创,转载请注明出处。

 

共两个类,一个是动态类处理的,一个是例外封装的,如下:

DynamicClass.java

package com.baseClass;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;

import com.Util;

/**
 * @author sidac

 * E_mail:sidac@sohu.com
 * 实现动态运行类的class
 */
public class DynamicClass {
 /**
  * @param runClass 要运行的类
  * @param runMethod 要运行的方法
  * @param argsList 参数
  * @return 类运行后的输出结果
  *
  * 各种可能的例外(错误)
  * @throws ClassNotFoundException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  * @throws InstantiationException
  * @throws MethodNotFoundException
  */
 public static Object runDynamicClass(String runClass, String runMethod, Object[] argsList)
   throws ClassNotFoundException, IllegalArgumentException,
   IllegalAccessException, InvocationTargetException,
   InstantiationException, MethodNotFoundException {
  
  boolean successfulExecute = false; //标识变量,记录方法是否得到正确运行
  Object ret = null; //执行结果

  Class objClass = Class.forName(runClass); //加载类
  Method[] methods = objClass.getMethods(); //取的类的方法
  
  //记录方法执行时出现的例外,以便当所有同名方法不能正确执行时抛出例外并提示
  IllegalArgumentException e1 = null;
  String rightMethodDeclare = "";
  
  for (int i = 0; i < methods.length; i++) { //编译类的方法
   if (methods[i].getName().equals(runMethod)) { //查找类的方法
    try{
     ret = methods[i].invoke(objClass.newInstance(), argsList); //动态执行
     
//     方法正确执行,则退出循环
     successfulExecute = true;
     break;
    }catch(IllegalArgumentException e){
     e1 = e;
     rightMethodDeclare += "/n/t" + methods[i].toString();
    }
   }
  }
  
//  销毁对象
  methods = null;
  objClass = null;
  
  if(successfulExecute){ //方法执行正确,返回执行结果
   return ret;
  }else if(!(e1 == null)){//如果参数不符合运行要求,抛出错误
   String args = "";
   if(argsList != null){
    for(int i = 0; i < argsList.length; i ++){
     args += (i > 0 ? ", /"" : "") + argsList[i].toString() + "/"";
    }
   }
   
   String errInfo = "Can't invoke " + runClass + "." + runMethod + "(" + args + ")";
   errInfo += "/nThe right method declare is:" + rightMethodDeclare;
   throw new IllegalArgumentException(errInfo);
  }else{ //未找到方法,抛出异常
   throw new MethodNotFoundException("Can't find method <" + runMethod + "> in class <" + runClass + ">");
  }
 }
 
 /**
  * @param runClass 要运行的类
  * @param runMethod 要运行的方法
  * @return 类运行后的输出结果
  *
  * 各种可能的例外(错误)
  * @throws IllegalArgumentException
  * @throws ClassNotFoundException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  * @throws InstantiationException
  * @throws MethodNotFoundException
  */
 public static Object runDynamicClass(String runClass, String runMethod) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, MethodNotFoundException{
//  执行调用,传入NULL参数,并返回结果
  Object[] argsList = null;
  return runDynamicClass(runClass, runMethod, argsList);
 }
 
 /**
  * @param runClass 要运行的类
  * @param runMethod 要运行的方法
  * @param argsList 参数
  * @return 类运行后的输出结果
  *
  * 各种可能的例外(错误)
  * @throws ClassNotFoundException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  * @throws InstantiationException
  * @throws MethodNotFoundException
  */
 public static Object runClassMethod(Object objClass, String runMethod, Object[] argsList)
   throws ClassNotFoundException, IllegalArgumentException,
   IllegalAccessException, InvocationTargetException,
   InstantiationException, MethodNotFoundException {
  
  if(objClass == null)
   return null;
  
  boolean successfulExecute = false; //标识变量,记录方法是否得到正确运行
  Object ret = null; //执行结果

  Method[] methods = (objClass.getClass()).getMethods(); //取的类的方法
  
  //记录方法执行时出现的例外,以便当所有同名方法不能正确执行时抛出例外并提示
  IllegalArgumentException e1 = null;
  String rightMethodDeclare = "";
  
  for (int i = 0; i < methods.length; i++) { //编译类的方法
   if (methods[i].getName().equals(runMethod)) { //查找类的方法
    try{
     ret = methods[i].invoke(objClass, argsList); //动态执行
     
//     方法正确执行,则退出循环
     successfulExecute = true;
     break;
    }catch(IllegalArgumentException e){
     e1 = e;
     rightMethodDeclare += "/n/t" + methods[i].toString();
    }
   }
  }
  
//  销毁对象
  methods = null;
  
  if(successfulExecute){ //方法执行正确,返回执行结果
   return ret;
  }else if(!(e1 == null)){//如果参数不符合运行要求,抛出错误
   String args = "";
   if(argsList != null){
    for(int i = 0; i < argsList.length; i ++){
     args += (i > 0 ? ", /"" : "") + argsList[i].toString() + "/"";
    }
   }
   
   String errInfo = "Can't invoke " + objClass.getClass().getName() + "." + runMethod + "(" + args + ")";
   errInfo += "/nThe right method declare is:" + rightMethodDeclare;
   throw new IllegalArgumentException(errInfo);
  }else{ //未找到方法,抛出异常
   throw new MethodNotFoundException("Can't find method <" + runMethod + "> in class <" + objClass.getClass().getName() + ">");
  }
 }
 
 /**
  * @param runClass 要运行的类
  * @param runMethod 要运行的方法
  * @return 类运行后的输出结果
  *
  * 各种可能的例外(错误)
  * @throws IllegalArgumentException
  * @throws ClassNotFoundException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  * @throws InstantiationException
  * @throws MethodNotFoundException
  */
 public static Object runClassMethod(Object objClass, String runMethod) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, MethodNotFoundException{
//  执行调用,传入NULL参数,并返回结果
  Object[] argsList = null;
  return runClassMethod(objClass, runMethod, argsList);
 }
 
 /**
  * 将结果记录存入对象
  * @param rs 结果集记录
  * @param obj 目标对象
  * @return 存入记录结果后的对象
  */
 public static boolean ResultSet2Object(ResultSet rs, Object object){
  if(rs == null || object == null)
   return false;
  
  try {
   if(rs.getRow() < 1){
    if(!rs.next())
     return false;
   }
   
   ResultSetMetaData rmd = rs.getMetaData();
   
   for(int i = 1; i <= rmd.getColumnCount(); i ++){
    setProperty(object, rmd.getColumnName(i), rs.getString(i) == null ? "" : rs.getString(i).trim());
   }
   
   return true;
  } catch (SQLException e) {
   e.printStackTrace();
  } catch (MethodNotFoundException e) {
   e.printStackTrace();
  }
  
  return false;
 }

 /**
  * 将结果集转换为对象向量表
  * @param rs 数据结果集
  * @param obj 记录对应的对象
  * @return 存入结果集记录的对象向量表
  */
 public static Vector ResultSet2ObjectVector(ResultSet rs, String objectClass){
  Vector result = null;
  ResultSetMetaData rmd = null;
  try {
   Class objClass = Class.forName(objectClass); //加载类

   while(rs.next()){
    if(result == null){//初始化
     result = new Vector();
     
     rmd = rs.getMetaData();
    }
    
    Object obj = objClass.newInstance();
    
    for(int i = 1; i <= rmd.getColumnCount(); i ++){
     setProperty(obj, rmd.getColumnName(i), rs.getString(i) == null ? "" : rs.getString(i).trim());
    }
    
    result.add(obj);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (MethodNotFoundException e) {
   e.printStackTrace();
  }
  
  return result;
 }

 /**
  * 动态提取类的属性值
  * @param obj 要提取属性值的类
  * @param name 属性名称
  * @return 返回结果
  * @throws MethodNotFoundException 方法无法找到例外
  */
 public static Object getProperty(Object obj, String name) throws MethodNotFoundException{
  boolean successfulExecute = false; //标识变量,记录方法是否得到正确运行
  Object result = null;

  Class objClass = obj.getClass();
  Method[] methods = objClass.getMethods(); //取的类的方法
  
  //记录方法执行时出现的例外,以便当所有同名方法不能正确执行时抛出例外并提示
  IllegalArgumentException e1 = null;
  String rightMethodDeclare = "";
  
  String methodName = "get" + Util.upperFirstChar(name);
  
  for (int i = 0; i < methods.length; i++) { //编译类的方法
   if (methods[i].getName().equals(methodName)) { //查找类的方法
    try{
     result = methods[i].invoke(obj, new Object[]{}); //动态执行
     
//     方法正确执行,则退出循环
     successfulExecute = true;
     break;
    }catch(IllegalArgumentException e){
     e1 = e;
     rightMethodDeclare += "/n/t" + methods[i].toString();
    } catch (IllegalAccessException e) {
     e.printStackTrace();
    } catch (InvocationTargetException e) {
     e.printStackTrace();
    }
   }
  }
  
  if(successfulExecute){ //方法执行正确,返回执行结果
   return result;
  }else if(!(e1 == null)){//如果参数不符合运行要求,抛出错误
   String errInfo = "/nCan't getProperty " + objClass.getName() + "." + methodName + "()";
   errInfo += "/nThe right method declare is:" + rightMethodDeclare;
   throw new IllegalArgumentException(errInfo);
  }else{ //未找到方法,抛出异常
   throw new MethodNotFoundException("Can't find method <" + methodName + "> in class <" + objClass.getName() + ">");
  }
 }

 /**
  * 动态为类设置属性值
  * @param obj 要设置属性值的类
  * @param name 属性名称
  * @param value 设置值
  * @return 返回结果
  * @throws MethodNotFoundException 方法无法找到例外
  */
 public static void setProperty(Object obj, String name, Object value) throws MethodNotFoundException{
  boolean successfulExecute = false; //标识变量,记录方法是否得到正确运行

  Class objClass = obj.getClass();
  Method[] methods = objClass.getMethods(); //取的类的方法
  
  //记录方法执行时出现的例外,以便当所有同名方法不能正确执行时抛出例外并提示
  IllegalArgumentException e1 = null;
  String rightMethodDeclare = "";
  
  String methodName = "set" + Util.upperFirstChar(name);
  Object[] para = new Object[]{value};
  
  for (int i = 0; i < methods.length; i++) { //编译类的方法
   if (methods[i].getName().equals(methodName)) { //查找类的方法
    try{
     methods[i].invoke(obj, para); //动态执行
     
//     方法正确执行,则退出循环
     successfulExecute = true;
     break;
    }catch(IllegalArgumentException e){
     e1 = e;
     rightMethodDeclare += "/n/t" + methods[i].toString();
    } catch (IllegalAccessException e) {
     e.printStackTrace();
    } catch (InvocationTargetException e) {
     e.printStackTrace();
    }
   }
  }
  
  if(successfulExecute){ //方法执行正确,返回执行结果
  }else if(!(e1 == null)){//如果参数不符合运行要求,抛出错误
   String errInfo = "/nCan't setProperty " + objClass.getName() + "." + methodName + "(" + value + ")";
   errInfo += "/nThe right method declare is:" + rightMethodDeclare;
   throw new IllegalArgumentException(errInfo);
  }else{ //未找到方法,抛出异常
   throw new MethodNotFoundException("Can't find method <" + methodName + "> in class <" + objClass.getName() + ">");
  }
 }
}

 

MethodNotFoundException.java

package com.baseClass;

/**
 * @author sidac

 * E_mail:sidac@sohu.com
 * DynamicRunClass 动态运行Class时找不到方法而抛出的例外
 */
public class MethodNotFoundException extends Exception {
    /**
  * throw Exception in the method RunClass of DynamicRunClass
  * when can't find the method to runed which the user specified
  */
 private static final long serialVersionUID = -1530441076621776685L;
 private Throwable ex;

    public MethodNotFoundException() {
     super((Throwable)null);  // Disallow initCause
    }

    public MethodNotFoundException(String s) {
     super(s, null);  //  Disallow initCause
    }

    public MethodNotFoundException(String s, Throwable ex) {
  super(s, null);  //  Disallow initCause
  this.ex = ex;
    }

    public Throwable getException() {
        return ex;
    }

    public Throwable getCause() {
        return ex;
    }
}

 

package com;

/**
 * @author sidac

 * E_mail:sidac@sohu.com
 *  提供基础处理与操作的类
 */
public class Util {

 /**
  * 大写首字母
  *
  * @param str
  *            需要转换的字符串
  * @return 转换后的字符串
  */
 public final static String upperFirstChar(String str) {
  if (str == null || str.equals("")) {
   return str;
  } else {
   StringBuilder result = new StringBuilder(str.substring(0, 1)
     .toUpperCase());
   result.append(str.substring(1).toLowerCase());
   return result.toString();
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值