# GenericSingletonFactory.java
public class GenericSingletonFactory {
private static applySame<Object> IDENTITY = new applySame<Object>() {
@Override
public Object apply(Object arg) {
return arg;
}
};
@SuppressWarnings("unchecked")
public static <T> applySame<T> identityFunction() {
return (applySame<T>) IDENTITY;
}
public static void main(String[] args) {
String[] strings = { "x", "y", "z" };
applySame<String> sameString = identityFunction();
for (String s : strings) {
System.out.println(sameString.apply(s));
}
Number[] numbers = {1, 2.0, 3L};
applySame<Number> sameNumber = identityFunction();
for (Number n : numbers) {
System.out.println(sameNumber.apply(n));
}
}
}
interface applySame<T> {
T apply(T arg);
}
# 결과
x
y
z
1
2.0
3
댓글 영역