7

Java CGLib Mixinクラスの使用法について、誰かが私に良い例を教えてくれますか? 私は掘り下げてきましたが、どれも十分に単純ではないようです。

4

3 に答える 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;
        }

    }

}

それが役立つことを願っています。

于 2011-07-28T14:17:55.797 に答える
1

質問は、インターフェースベースの mixin ケースだけよりも広いため、2 つの任意のクラスを持つ CGLIB mixin の例を次に示します。

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);
    }

}
于 2013-08-01T08:58:40.390 に答える
0

この例は高度なエンハンサーで動作し、ミックスインのように動作します: http://www.jroller.com/melix/entry/alternative_to_delegate_pattern_with

于 2011-07-19T13:16:58.633 に答える