在Java中,泛型和反射的結合使用可以帶來很多強大的功能,如動態創建對象、調用方法、訪問字段等。以下是一些使用泛型和反射結合的技巧:
public class GenericFactory {
public static <T> T createInstance(Class<T> clazz) throws Exception {
return clazz.getDeclaredConstructor().newInstance();
}
}
public class GenericMethodInvoker {
public static <T> void invokeMethod(Object target, Class<T> returnType, String methodName, Object... args) throws Exception {
Method method = target.getClass().getMethod(methodName, getParameterTypes(args));
method.invoke(target, args);
}
private static Class<?>[] getParameterTypes(Object... args) {
Class<?>[] parameterTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
parameterTypes[i] = args[i].getClass();
}
return parameterTypes;
}
}
public class GenericFieldAccessor {
public static <T> void setField(Object target, Class<T> fieldType, String fieldName, T value) throws Exception {
Field field = target.getClass().getField(fieldName);
field.set(target, value);
}
public static <T> T getField(Object target, Class<T> fieldType, String fieldName) throws Exception {
Field field = target.getClass().getField(fieldName);
return fieldType.cast(field.get(target));
}
}
public class TypeUtils {
public static <T> T cast(Object obj, Class<T> targetType) {
if (obj == null || targetType == null) {
return null;
}
return targetType.cast(obj);
}
public static <T> boolean isInstance(Object obj, Class<T> targetType) {
if (obj == null || targetType == null) {
return false;
}
return targetType.isInstance(obj);
}
}
這些技巧可以幫助你更好地利用泛型和反射來編寫更靈活、更動態的代碼。但請注意,反射操作通常比直接操作對象要慢,因此在使用反射時要權衡性能和靈活性。