欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java利用反射实现动态代理示例

程序员文章站 2024-02-28 18:09:52
复制代码 代码如下:package com.et59.cus.domain.dao.ex; import java.lang.reflect.field;import j...

复制代码 代码如下:

package com.et59.cus.domain.dao.ex;

import java.lang.reflect.field;
import java.lang.reflect.method;
import java.lang.reflect.modifier;

import org.apache.log4j.logger;
/**
 *
 * <p>title: reflectutil.java</p>
 * <p>description: 反射</p>
 * <p>company: 点滴工作室</p>
 * @version 2.0
 *
 */
public class reflectutil {

    private static final logger log = logger.getlogger(reflectutil.class);

    @suppresswarnings({ "rawtypes", "unchecked" })
 public static void setfieldvalue(object target, string fname, class ftype,
            object fvalue) {
        if (target == null
                || fname == null
                || "".equals(fname)
                || (fvalue != null && !ftype.isassignablefrom(fvalue.getclass()))) {
            return;
        }
        class clazz = target.getclass();
        try {
            method method = clazz.getdeclaredmethod("set"
                    + character.touppercase(fname.charat(0))
                    + fname.substring(1), ftype);
            if (!modifier.ispublic(method.getmodifiers())) {
                method.setaccessible(true);
            }
            method.invoke(target, fvalue);

        } catch (exception me) {
            if (log.isdebugenabled()) {
               // log.debug("me异常-------->:"+me);
            }
            try {
                field field = clazz.getdeclaredfield(fname);
                if (!modifier.ispublic(field.getmodifiers())) {
                    field.setaccessible(true);
                }
                field.set(target, fvalue);
            } catch (exception fe) {
                if (log.isdebugenabled()) {
                    log.debug("fe----------->"+fe);
                }
            }
        }
    }
}