//一个二元的元组类
public class TwoTuple<A, B> { //A,B就是泛型形参
public final A first;
public final B second;
public TwoTuple(A a, B b) {
first = a;
second = b;
}
public String toString() {
return "(" + first + "," + second + ")";
}
}
public class Main {
public static void main(String[] args) {
TwoTuple<String, Integer> tuple = new TwoTuple<>("hello", 123); //这里省略的<String, Integer>就是泛型实参
System.out.println(tuple);
}
}
//生成器
public interface Generator<T> {
T next();
}
//实现接口时传入泛型实参
public class NumGen implements Generator<Integer> {
@Override
public Integer next() { //返回值为实参
return null;
}
}
//实现接口时不传入泛型实参
public class CoffeeGen<T> implements Generator<T> {
@Override
public T next() { //返回值依然为形参
return null;
}
}
public class GenericMethods {
public <T> void f(T x) {
System.out.println(x.getClass().getName());
}
public static void main(String[] args) {
GenericMethods gen = new GenericMethods();
gen.f("hello"); //类型参数推断
// gen.<String>f("hello"); //显示的类型说明
}
}
public static void main(String[] args) throws Exception {
List<Integer> list = new ArrayList<>();
list.add(0);
//绕过泛型的静态检查插入字母x
Method add = list.getClass().getMethod("add", Object.class);
add.invoke(list, "x");
System.out.println(list); //列表输出正常
Integer i = list.get(1); //泛型转型失败ClassCastException: java.lang.String cannot be cast to java.lang.Integer
System.out.println(i);
}
public class LostInformation {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
List<Double> list = new ArrayList<>();
System.out.println(Arrays.toString(map.getClass().getTypeParameters()));
System.out.println(Arrays.toString(list.getClass().getTypeParameters()));
}
}
public class Test {
public void method1(List<String> args) { //泛型参数
System.out.println(args);
}
public void method2(List args) { //原生类型
System.out.println(args);
}
public static void main(String[] args) {
List<String> list1 = new ArrayList<>(Arrays.asList("a", "b", "c"));
List list2 = new ArrayList(Arrays.asList("a", 1, "c"));
Test test = new Test();
test.method1(list1);
test.method1(list2); //泛型参数接收原生类型
test.method2(list1); //原生类型接收泛型参数
test.method2(list2);
}
}
public class Erased<T> {
private final int SIZE = 100;
public void f(Object arg) {
// if (arg instanceof T) {} //Error 类型判断
// T var = new T(); //Error 创建实例对象
// T[] array = new T[SIZE]; //Error 创建泛型数组
T array = (T) new Object(); //转型
System.out.println(array); //无论T是传进来什么类型,输出都是Object,已经被擦除
}
public static void main(String[] args) {
Erased<Date> erased = new Erased<>();
erased.f(new Date());
}
}
public class ClassTypeCapture<T> {
private final int SIZE = 100;
private Class<T> kind; //类型标签
public ClassTypeCapture(Class<T> kind) {
this.kind = kind;
}
public void f(Object arg) throws Exception {
System.out.println(kind.isInstance(arg)); //类型判断
T t = kind.newInstance(); //创建实例对象
System.out.println(t);
T[] array = (T[]) Array.newInstance(kind, SIZE); //创建泛型数组
System.out.println(array);
T t1 = kind.cast(arg); //转型
System.out.println(t1);
}
public static void main(String[] args) throws Exception {
ClassTypeCapture<Date> capture = new ClassTypeCapture<>(Date.class);
capture.f(new Date());
}
}
public interface Factory<T> {
T create();
}
public class IntegerFactory implements Factory<Integer> {
@Override
public Integer create() {
return new Integer(0);
}
}
public class StringFactory implements Factory<String> {
@Override
public String create() {
return new String("string");
}
}
public class FactoryMain {
static <T, F extends Factory<T>> T newInstance(F factory) {
return factory.create();
}
public static void main(String[] args) {
Integer i = newInstance(new IntegerFactory());
System.out.println(i);
String str = newInstance(new StringFactory());
System.out.println(str);
}
}
public abstract class Creator<T> {
private T element;
public Creator() {
this.element = create();
}
abstract T create(); //模板方法
public void f() {
System.out.println(element.getClass().getName());
}
}
public class IntegerCreator extends Creator<Integer> {
@Override
Integer create() {
return new Integer(0);
}
}
public class CreatorMain {
public static void main(String[] args) {
Creator<Integer> creator = new IntegerCreator();
creator.f();
}
}
public class Fruit {
}
public class Apple extends Fruit {
}
public class CovariantArrays {
public static void main(String[] args) {
Fruit[] fruits = new Apple[10];
fruits[1] = new Apple();
fruits[0] = new Fruit(); //可以编译通过,运行报错
}
}
public static void main(String[] args) {
List<? extends Fruit> fruits = new ArrayList<>();
fruits.add(new Apple()); //Error 编译错误
fruits.add(new Fruit()); //Error 编译错误
fruits.add(null);
Fruit fruit = fruits.get(0); //安全的
System.out.println(fruit);
}
public static void main(String[] args) {
List<? super Fruit> fruits = Arrays.asList();
fruits.add(new Apple()); //安全
fruits.add(new Fruit()); //安全
fruits.add(null);
Fruit fruit = fruits.get(0);//Error 编译错误
System.out.println(fruit);
}
public static void main(String[] args) {
List<?> fruits = Arrays.asList();
fruits.add(new Apple()); //Error 编译错误
fruits.add(new Fruit()); //Error 编译错误
fruits.add(null);
Fruit fruit = fruits.get(0);//Error 编译错误
fruits.add(new Object()); //Error 编译错误
Object obj = fruits.get(0); //安全
System.out.println(obj);
}
public class SelfBounded<T extends SelfBounded<T>> {
T element;
public SelfBounded<T> set(T element) {
this.element = element;
return this;
}
public T getElement() {
return element;
}
}
class A extends SelfBounded<A> {}
class B extends SelfBounded<A> {} ///也是ok的,因为A 也是SelfBounded
class C {}
class D extends SelfBounded<C> {} //Error 编译错误,因为C并不是SelfBounded
interface Test2<T extends Exception> {
void test() throws T;
}
//说话的能力
interface ISay {
void say();
}
class SayImpl implements ISay {
@Override
public void say() {
System.out.println("hello");
}
}
//报时的能力
interface IDate {
void now();
}
class DateImpl implements IDate {
@Override
public void now() {
System.out.println(new Date());
}
}
//唱歌的能力
interface ISing {
void sing();
}
class SingImpl implements ISing {
@Override
public void sing() {
System.out.println("lalalalalala!");
}
}
class Mix implements InvocationHandler { //动态代理
private Map<String, Object> delegates = new HashMap<>();
public Mix(Object ...args) {
for (Object obj : args) {
Class<?> clazz = obj.getClass();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (!delegates.containsKey(method.getName())) {
delegates.put(method.getName(), obj);
}
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object delegate = delegates.get(method.getName());
return method.invoke(delegate, args);
}
public static Object newInstance(Class[] clazzes, Object[] objects) {
return Proxy.newProxyInstance(Mix.class.getClassLoader(), clazzes, new Mix(objects));
}
}
public class Test1 {
public static void main(String[] args) {
//混合三种能力
Object mixObj = Mix.newInstance(
new Class[]{ISing.class, IDate.class, ISay.class},
new Object[]{new SingImpl(), new DateImpl(), new SayImpl()});
ISing singObj = (ISing) mixObj;
singObj.sing();
ISay sayObj = (ISay) mixObj;
sayObj.say();
IDate dateObj = (IDate) mixObj;
dateObj.now();
}
}
public class Test3 {
public static void perform(Object obj){
Class<?> clazz = obj.getClass();
try {
Method say = clazz.getMethod("say");
say.invoke(obj);
} catch (Exception e) {
System.out.println(obj + " can not say");
}
try {
Method say = clazz.getMethod("sing");
say.invoke(obj);
} catch (Exception e) {
System.out.println(obj + " can not sing");
}
}
public static void main(String[] args) {
perform(new SingImpl());
System.out.println("----------");
perform(new SayImpl());
}
}
interface Strategy<T, R> {
R operation(T obj1, T obj2);
}
//整数相加操作
class IntegerAddOperation implements Strategy<Integer, Integer> {
@Override
public Integer operation(Integer obj1, Integer obj2) {
return obj1 + obj2;
}
}
//字符串比较操作
class StringCompareOperation implements Strategy<String, String> {
@Override
public String operation(String obj1, String obj2) {
Integer result = obj1.compareTo(obj2);
if ( result == 0) {
return obj1 + " == " + obj2;
} else if (result > 0) {
return obj1 + " > " + obj2;
} else {
return obj1 + " < " + obj2;
}
}
}
public class Context {
public static void execute( Object obj1, Object obj2,Strategy strategy) {
Object result = strategy.operation(obj1, obj2);
System.out.println(result);
}
public static void main(String[] args) {
execute(1, 2, new IntegerAddOperation());
execute("today", "tomorrow", new StringCompareOperation());
}
}
原文:https://www.cnblogs.com/shineon/p/11599403.html