在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);
}
}
这些技巧可以帮助你更好地利用泛型和反射来编写更灵活、更动态的代码。但请注意,反射操作通常比直接操作对象要慢,因此在使用反射时要权衡性能和灵活性。