CGLib混入实例

7
有没有人能给我一个Java CGLib Mixin类使用的好例子? 我已经找了很久,但它们似乎都不够简单易懂。请参考Mixin官方文档
3个回答

8
足够简单:
import static org.junit.Assert.*;
import net.sf.cglib.proxy.Mixin;

import org.junit.Before;
import org.junit.Test;


public class MixinTest {

    @Test
    public void test() {
        Mixin mixin = Mixin.create(new Object[]{ new Class1(), new Class2() });
        assertEquals(1, ((Interface1)mixin).method1());
        assertEquals(2, ((Interface2)mixin).method2());
    }

    private interface Interface1 {
        public int method1();
    }

    private interface Interface2 {
        public int method2();
    }

    private static class Class1 implements Interface1 {

        @Override
        public int method1() {
            return 1;
        }

    }

    private static class Class2 implements Interface2 {

        @Override
        public int method2() {
            return 2;
        }

    }

}

希望这能帮到你。

1
这个问题不仅限于基于接口的混合案例,所以这里提供一个使用CGLIB混合的示例,其中涉及两个任意类:
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Locale;

import net.sf.cglib.proxy.Mixin;
import net.sf.cglib.proxy.Mixin.Generator;

public class CglibTest {

    public static void main(String[] args) throws Exception {
        Generator gen = new Generator();
        gen.setStyle(Mixin.STYLE_EVERYTHING);
        gen.setDelegates(new Object[]{ Charset.defaultCharset(), Locale.getDefault()});
        Mixin mixin = gen.create();
        System.out.println(invokeMethod(mixin, "displayName"));
        System.out.println(invokeMethod(mixin, "getCountry"));
    }  


    public static Object invokeMethod(Object target, String methodName) throws Exception {
        Method method = target.getClass().getMethod(methodName);
        return method.invoke(target);
    }

}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接