在aspectj中声明泛型父语句

时间:2014-04-08 12:04:17

标签: aspectj

是否可以将泛型类型与declare parent一起使用,以便使用泛型定义的类实现具有相同泛型类型的接口

declare parents: AClass<Generic1,Generic2> implements

AnInterface<Generic1,Generic2>

我所说的是是否可以将孩子的泛型类型传递给父母

1 个答案:

答案 0 :(得分:0)

有点儿。看看这个:

通用类:

package de.scrum_master.app;

public class KeyValuePair<K,V> {
    private K key;
    private V value;

    KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() { return key; }
    public V getValue() { return value; }

    @Override
    public String toString() {
        return "KeyValuePair [key=" + key + ", value=" + value + "]";
    }
}

通用界面:

package de.scrum_master.app;

public interface KeyValueComparator<K, V> {
    boolean equalsKey(K otherKey);
    boolean equalsValue(V otherValue);
}

ITD方面:

ITD(类型间定义)确保该类实现接口并同时获取接口的方法实现。

package de.scrum_master.aspect;

import de.scrum_master.app.KeyValuePair;
import de.scrum_master.app.KeyValueComparator;

public aspect InterfaceIntroductionAspect {
    declare parents : KeyValuePair implements KeyValueComparator;

    public boolean KeyValuePair.equalsKey(K otherKey) {
        return this.getKey().equals(otherKey);
    }

    public boolean KeyValuePair.equalsValue(V otherValue) {
        return this.getValue().equals(otherValue);
    }
}

驱动程序应用程序:

创建两种不同类型的类对象,并尝试将它们都转换为引入的接口:

package de.scrum_master.app;

public class Application {
    public static void main(String[] args) {
        KeyValuePair<Integer, String> pair1 = new KeyValuePair<>(11, "eleven");
        System.out.println(pair1);
        KeyValueComparator<Integer, String> comparator1 = (KeyValueComparator<Integer, String>) pair1;
        System.out.println("equalsKey   = " + comparator1.equalsKey(12));
        System.out.println("equalsValue = " + comparator1.equalsValue("eleven"));

        KeyValuePair<String, Integer> pair2 = new KeyValuePair<>("twelve", 12);
        System.out.println(pair2);
        KeyValueComparator<String, Integer> comparator2 = (KeyValueComparator<String, Integer>) pair2;
        System.out.println("equalsKey   = " + comparator2.equalsKey("twelve"));
        System.out.println("equalsValue = " + comparator2.equalsValue(11));
    }
}

<强>输出:

KeyValuePair [key=11, value=eleven]
equalsKey   = false
equalsValue = true
KeyValuePair [key=twelve, value=12]
equalsKey   = true
equalsValue = false