OSS上传文件返回前端上传进度三种方式

- 日理万妓 2022-12-29 04:40 868阅读 0赞

一、采用前端定时轮询请求接口

注意:采用session存放文件上传进度数据,适合jsp或者模板引擎页面,但是如果前后的分离,请采用redis或者MQ(消息队列)方式,将进度存入仓库中,然后通过标识读取数据,完成之后请重置或者删除标识。

1.1、上传文件

  1. @Value("${oss.endpoint}")
  2. private String endpoint;
  3. @Value("${oss.accessKeyId}")
  4. private String accessKeyId;
  5. @Value("${oss.accessKeySecret}")
  6. private String accessKeySecret;
  7. @Value("${oss.bucketName}")
  8. private String bucketName;
  9. @PostMapping("/upload")
  10. public Object doUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
  11. if (file == null || file.isEmpty()) {
  12. return BaseResponse.fail("上传的文件是空文件!");
  13. }
  14. String fileName = file.getOriginalFilename();
  15. FileUtils utils = new FileUtils();
  16. File files = null;
  17. try {
  18. files = File.createTempFile("tmp", null);
  19. file.transferTo(files);
  20. files.deleteOnExit();
  21. } catch (Exception e) {
  22. log.error("流转文件失败:{}",e);
  23. }
  24. String url = utils.doUpload(fileName, files, endpoint, accessKeyId, accessKeySecret, bucketName, request.getSession());
  25. Map<String, Object> map = new HashMap<>(1);
  26. map.put("url", url);
  27. map.put("fileName", fileName);
  28. return map;
  29. }

1.2、获取进度

  1. /** * 获取进度数据 * @param request * @return */
  2. @GetMapping("/percent")
  3. public Object getUploadPercent(HttpServletRequest request){
  4. HttpSession session = request.getSession();
  5. int percent = session.getAttribute("upload_percent") == null ? 0: (Integer)session.getAttribute("upload_percent");
  6. Map<String, Object> map = new HashMap<>(1);
  7. map.put("percent", percent);
  8. return map;
  9. }
  10. /** * 重置上传进度 * @param request */
  11. @GetMapping("/percent/reset")
  12. public void resetPercent(HttpServletRequest request){
  13. HttpSession session = request.getSession();
  14. session.setAttribute("upload_percent",0);
  15. }

1.3、上传文件工具类

  1. import com.aliyun.oss.ClientConfiguration;
  2. import com.aliyun.oss.OSSClient;
  3. import com.aliyun.oss.common.comm.Protocol;
  4. import com.aliyun.oss.model.PutObjectRequest;
  5. import lombok.extern.slf4j.Slf4j;
  6. import javax.servlet.http.HttpSession;
  7. import java.io.*;
  8. import java.net.URL;
  9. import java.util.Date;
  10. import java.util.concurrent.TimeUnit;
  11. @Slf4j
  12. public class FileUtils {
  13. public String doUpload(String key, File files, String endpoint, String accessKeyId, String accessKeySecret, String bucketName, HttpSession session) {
  14. String keys = "test/"+key;
  15. try {
  16. ClientConfiguration config = new ClientConfiguration();
  17. config.setProtocol(Protocol.HTTPS);
  18. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, config);
  19. ossClient.putObject(new PutObjectRequest(bucketName, keys, files).withProgressListener(new PutObjectProgressListener(session)));
  20. Date expiration = new Date(System.currentTimeMillis() + EXPIRE_TIME);
  21. URL url = ossClient.generatePresignedUrl(bucketName, keys, expiration);
  22. ossClient.shutdown();
  23. return String.valueOf(url);
  24. } catch (Exception e) {
  25. log.error(e.getMessage(), e);
  26. throw new IllegalStateException("文件上传到阿里云OSS服务报错!", e);
  27. }
  28. }
  29. }

1.4、获取进度工具类

  1. import com.aliyun.oss.event.ProgressEvent;
  2. import com.aliyun.oss.event.ProgressEventType;
  3. import com.aliyun.oss.event.ProgressListener;
  4. import lombok.extern.slf4j.Slf4j;
  5. import javax.servlet.http.HttpSession;
  6. /** * ossClient.putObject, ossClient.getObject, ossClient.uploadPart方法支持进度条功能. * ossClient.uploadFile和ossClient.downloadFile方法不支持进度条功能. * 简单上传进度条监听器 * https://help.aliyun.com/document_detail/84796.html?spm=a2c4g.11186623.6.791.40554d83cDiWSN */
  7. @Slf4j
  8. public class PutObjectProgressListener implements ProgressListener {
  9. private long bytesWritten = 0;
  10. private long totalBytes = -1;
  11. private HttpSession session;
  12. private boolean succeed = false;
  13. private int percent = 0;
  14. public PutObjectProgressListener(HttpSession mSession) {
  15. this.session = mSession;
  16. session.setAttribute("upload_percent", percent);
  17. }
  18. @Override
  19. public void progressChanged(ProgressEvent progressEvent) {
  20. long bytes = progressEvent.getBytes();
  21. ProgressEventType eventType = progressEvent.getEventType();
  22. switch (eventType) {
  23. case TRANSFER_STARTED_EVENT:
  24. log.debug("Start to upload......");
  25. break;
  26. case REQUEST_CONTENT_LENGTH_EVENT:
  27. this.totalBytes = bytes;
  28. log.debug(this.totalBytes + " bytes in total will be uploaded to OSS");
  29. break;
  30. case REQUEST_BYTE_TRANSFER_EVENT:
  31. this.bytesWritten += bytes;
  32. if (this.totalBytes != -1) {
  33. int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
  34. log.debug(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
  35. session.setAttribute("upload_percent", percent);
  36. } else {
  37. log.debug(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
  38. }
  39. break;
  40. case TRANSFER_COMPLETED_EVENT:
  41. this.succeed = true;
  42. log.debug("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
  43. break;
  44. case TRANSFER_FAILED_EVENT:
  45. log.debug("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
  46. break;
  47. default:
  48. break;
  49. }
  50. }
  51. public boolean isSucceed(){
  52. return succeed;
  53. }
  54. }

二、采用stomp+websocket推送模式

2.1、依赖

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-messaging</artifactId>
  4. <version>5.2.6.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework</groupId>
  8. <artifactId>spring-websocket</artifactId>
  9. <version>5.1.8.RELEASE</version>
  10. </dependency>

2.2、客户端配置

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
  3. import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
  4. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  5. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  6. //注解开启STOMP协议来传输基于代理的消息,此时控制器支持使用@MessageMapping
  7. @Configuration
  8. @EnableWebSocketMessageBroker
  9. public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
  10. @Override
  11. public void configureMessageBroker(MessageBrokerRegistry config) {
  12. //topic用来广播,user用来实现p2p
  13. config.enableSimpleBroker("/topic","/user");
  14. }
  15. @Override
  16. public void registerStompEndpoints(StompEndpointRegistry registry) {
  17. registry.addEndpoint("/webServer").withSockJS();
  18. //注册两个STOMP的endpoint,分别用于广播和点对点
  19. registry.addEndpoint("/queueServer").withSockJS();
  20. }
  21. }

2.3、上传文件

  1. @Value("${oss.endpoint}")
  2. private String endpoint;
  3. @Value("${oss.accessKeyId}")
  4. private String accessKeyId;
  5. @Value("${oss.accessKeySecret}")
  6. private String accessKeySecret;
  7. @Value("${oss.bucketName}")
  8. private String bucketName;
  9. @PostMapping("/upload")
  10. public Object doUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
  11. if (file == null || file.isEmpty()) {
  12. return BaseResponse.fail("上传的文件是空文件!");
  13. }
  14. String fileName = file.getOriginalFilename();
  15. FileUtils utils = new FileUtils();
  16. File files = null;
  17. try {
  18. files = File.createTempFile("tmp", null);
  19. file.transferTo(files);
  20. files.deleteOnExit();
  21. } catch (Exception e) {
  22. log.error("流转文件失败:{}",e);
  23. }
  24. String url = utils.doUpload(fileName, files, endpoint, accessKeyId, accessKeySecret, bucketName, request.getSession());
  25. Map<String, Object> map = new HashMap<>(1);
  26. map.put("url", url);
  27. map.put("fileName", fileName);
  28. return map;
  29. }

2.4、上传文件工具类

  1. import com.aliyun.oss.ClientConfiguration;
  2. import com.aliyun.oss.OSSClient;
  3. import com.aliyun.oss.common.comm.Protocol;
  4. import com.aliyun.oss.model.PutObjectRequest;
  5. import lombok.extern.slf4j.Slf4j;
  6. import javax.servlet.http.HttpSession;
  7. import java.io.*;
  8. import java.net.URL;
  9. import java.util.Date;
  10. import java.util.concurrent.TimeUnit;
  11. @Slf4j
  12. public class FileUtils {
  13. public String doUpload(String key, File files, String endpoint, String accessKeyId, String accessKeySecret, String bucketName, HttpSession session) {
  14. String keys = "test/"+key;
  15. try {
  16. ClientConfiguration config = new ClientConfiguration();
  17. config.setProtocol(Protocol.HTTPS);
  18. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, config);
  19. ossClient.putObject(new PutObjectRequest(bucketName, keys, files).withProgressListener(new PutObjectProgressListener(session)));
  20. Date expiration = new Date(System.currentTimeMillis() + EXPIRE_TIME);
  21. URL url = ossClient.generatePresignedUrl(bucketName, keys, expiration);
  22. ossClient.shutdown();
  23. return String.valueOf(url);
  24. } catch (Exception e) {
  25. log.error(e.getMessage(), e);
  26. throw new IllegalStateException("文件上传到阿里云OSS服务报错!", e);
  27. }
  28. }
  29. }

2.5、推送方式

  1. import com.aliyun.oss.event.ProgressEvent;
  2. import com.aliyun.oss.event.ProgressEventType;
  3. import com.aliyun.oss.event.ProgressListener;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.messaging.simp.SimpMessagingTemplate;
  7. import org.springframework.stereotype.Service;
  8. import javax.servlet.http.HttpSession;
  9. /** * ossClient.putObject, ossClient.getObject, ossClient.uploadPart方法支持进度条功能. * ossClient.uploadFile和ossClient.downloadFile方法不支持进度条功能. * 简单上传进度条监听器 * https://help.aliyun.com/document_detail/84796.html?spm=a2c4g.11186623.6.791.40554d83cDiWSN */
  10. @Slf4j
  11. @Service
  12. public class PutObjectProgressListener implements ProgressListener {
  13. @Autowired
  14. public SimpMessagingTemplate simpMessagingTemplate;
  15. private long bytesWritten = 0;
  16. private long totalBytes = -1;
  17. private HttpSession session;
  18. private boolean succeed = false;
  19. private int percent = 0;
  20. public PutObjectProgressListener(HttpSession mSession) {
  21. this.session = mSession;
  22. }
  23. @Override
  24. public void progressChanged(ProgressEvent progressEvent) {
  25. long bytes = progressEvent.getBytes();
  26. ProgressEventType eventType = progressEvent.getEventType();
  27. switch (eventType) {
  28. case TRANSFER_STARTED_EVENT:
  29. log.debug("Start to upload......");
  30. break;
  31. case REQUEST_CONTENT_LENGTH_EVENT:
  32. this.totalBytes = bytes;
  33. log.debug(this.totalBytes + " bytes in total will be uploaded to OSS");
  34. break;
  35. case REQUEST_BYTE_TRANSFER_EVENT:
  36. this.bytesWritten += bytes;
  37. if (this.totalBytes != -1) {
  38. int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
  39. log.debug(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
  40. // 通过websocket 推送
  41. Map<String, Object> map = new HashMap<>(1);
  42. map.put("percent", percent);
  43. simpMessagingTemplate.convertAndSend("/topic/percent", map);
  44. } else {
  45. log.debug(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
  46. }
  47. break;
  48. case TRANSFER_COMPLETED_EVENT:
  49. this.succeed = true;
  50. log.debug("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
  51. break;
  52. case TRANSFER_FAILED_EVENT:
  53. log.debug("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
  54. break;
  55. default:
  56. break;
  57. }
  58. }
  59. public boolean isSucceed(){
  60. return succeed;
  61. }
  62. }

三、采用Servlet3.1长轮询模式

3.1、长轮询获取进度

  1. /** * guava中的Multimap,多值map,对map的增强,一个key可以保持多个value */
  2. private Multimap<String, DeferredResult<Object>> watchRequests = Multimaps.synchronizedSetMultimap(HashMultimap.create());
  3. /** * 前端长轮询 当接口返回304 一直请求 直到返回结果 */
  4. @RequestMapping(value = "/watch", method = RequestMethod.GET, produces = "text/html")
  5. public DeferredResult<Object> watch(HttpServletRequest request) {
  6. log.info("Request received");
  7. ResponseEntity<Object> NOT_MODIFIED_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
  8. DeferredResult<Object> deferredResult = new DeferredResult<>(5000L, NOT_MODIFIED_RESPONSE);
  9. /** * 当deferredResult完成时(不论是超时还是异常还是正常完成),移除watchRequests中相应的watch key */
  10. deferredResult.onCompletion(() -> {
  11. log.info("remove key:" + request.getSession().getId());
  12. watchRequests.remove(request.getSession().getId(), deferredResult);
  13. });
  14. deferredResult.onTimeout(()-> log.info("onTimeout()" ));
  15. watchRequests.put(request.getSession().getId(), deferredResult);
  16. log.info("Servlet thread released");
  17. return deferredResult;
  18. }
  19. /** * 发布数据 请求接口方式 反射调用方式 * @param sessionId * @return */
  20. @RequestMapping(value = "/publish", method = RequestMethod.GET, produces = "text/html")
  21. public Object publish(@RequestParam("sessionId") String sessionId, @RequestParam("percent") Integer percent) {
  22. if (watchRequests.containsKey(sessionId)) {
  23. Collection<DeferredResult<Object>> deferredResults = watchRequests.get(sessionId);
  24. //通知所有watch这个sessionId变更的长轮训配置变更结果
  25. for (DeferredResult<Object> deferredResult : deferredResults) {
  26. //deferredResult一旦执行了setResult()方法,就说明DeferredResult正常完成了,会立即把结果返回给客户端
  27. Map<String, Object> map = new HashMap<>(2);
  28. map.put("sessionId", sessionId);
  29. map.put("percent", percent);
  30. deferredResult.setResult(map);
  31. }
  32. }
  33. Map<String, Object> map = new HashMap<>(2);
  34. map.put("code", "success");
  35. return map;
  36. }

3.2、发布数据

  1. import com.aliyun.oss.event.ProgressEvent;
  2. import com.aliyun.oss.event.ProgressEventType;
  3. import com.aliyun.oss.event.ProgressListener;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.ApplicationContext;
  7. import org.springframework.stereotype.Component;
  8. import javax.servlet.http.HttpSession;
  9. import java.lang.reflect.Method;
  10. /** * ossClient.putObject, ossClient.getObject, ossClient.uploadPart方法支持进度条功能. * ossClient.uploadFile和ossClient.downloadFile方法不支持进度条功能. * 简单上传进度条监听器 * https://help.aliyun.com/document_detail/84796.html?spm=a2c4g.11186623.6.791.40554d83cDiWSN */
  11. @Slf4j
  12. @Component
  13. public class PutObjectProgressListener implements ProgressListener {
  14. @Autowired
  15. private ApplicationContext applicationContext;
  16. private long bytesWritten = 0;
  17. private long totalBytes = -1;
  18. private HttpSession session;
  19. private boolean succeed = false;
  20. private int percent = 0;
  21. public PutObjectProgressListener(HttpSession mSession) {
  22. this.session = mSession;
  23. }
  24. @Override
  25. public void progressChanged(ProgressEvent progressEvent) {
  26. long bytes = progressEvent.getBytes();
  27. ProgressEventType eventType = progressEvent.getEventType();
  28. switch (eventType) {
  29. case TRANSFER_STARTED_EVENT:
  30. log.debug("Start to upload......");
  31. break;
  32. case REQUEST_CONTENT_LENGTH_EVENT:
  33. this.totalBytes = bytes;
  34. log.debug(this.totalBytes + " bytes in total will be uploaded to OSS");
  35. break;
  36. case REQUEST_BYTE_TRANSFER_EVENT:
  37. this.bytesWritten += bytes;
  38. if (this.totalBytes != -1) {
  39. int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
  40. log.debug(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
  41. publish(session.getId(), percent);
  42. } else {
  43. log.debug(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
  44. }
  45. break;
  46. case TRANSFER_COMPLETED_EVENT:
  47. this.succeed = true;
  48. log.debug("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
  49. break;
  50. case TRANSFER_FAILED_EVENT:
  51. log.debug("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
  52. break;
  53. default:
  54. break;
  55. }
  56. }
  57. public boolean isSucceed(){
  58. return succeed;
  59. }
  60. /** * 通过反射调用接口 */
  61. private void publish(String sessionId, Integer percent) {
  62. Class<?> clazz = ReflectUtil.forName("cn.com.*.controller.upload.FileUploadController");
  63. Object bean = applicationContext.getBean(clazz);
  64. Method method = ReflectUtil.findMethod(clazz, "publish", String.class, Integer.class);
  65. ReflectUtil.invokeMethod(method, bean, sessionId, percent);
  66. }
  67. }

3.3、上传文件

  1. @Value("${oss.endpoint}")
  2. private String endpoint;
  3. @Value("${oss.accessKeyId}")
  4. private String accessKeyId;
  5. @Value("${oss.accessKeySecret}")
  6. private String accessKeySecret;
  7. @Value("${oss.bucketName}")
  8. private String bucketName;
  9. @PostMapping("/upload")
  10. public Object doUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
  11. if (file == null || file.isEmpty()) {
  12. return BaseResponse.fail("上传的文件是空文件!");
  13. }
  14. String fileName = file.getOriginalFilename();
  15. FileUtils utils = new FileUtils();
  16. File files = null;
  17. try {
  18. files = File.createTempFile("tmp", null);
  19. file.transferTo(files);
  20. files.deleteOnExit();
  21. } catch (Exception e) {
  22. log.error("流转文件失败:{}",e);
  23. }
  24. String url = utils.doUpload(fileName, files, endpoint, accessKeyId, accessKeySecret, bucketName, request.getSession());
  25. Map<String, Object> map = new HashMap<>(1);
  26. map.put("url", url);
  27. map.put("fileName", fileName);
  28. return map;
  29. }

3.4、上传文件工具类

  1. import com.aliyun.oss.ClientConfiguration;
  2. import com.aliyun.oss.OSSClient;
  3. import com.aliyun.oss.common.comm.Protocol;
  4. import com.aliyun.oss.model.PutObjectRequest;
  5. import lombok.extern.slf4j.Slf4j;
  6. import javax.servlet.http.HttpSession;
  7. import java.io.*;
  8. import java.net.URL;
  9. import java.util.Date;
  10. import java.util.concurrent.TimeUnit;
  11. @Slf4j
  12. public class FileUtils {
  13. public String doUpload(String key, File files, String endpoint, String accessKeyId, String accessKeySecret, String bucketName, HttpSession session) {
  14. String keys = "test/"+key;
  15. try {
  16. ClientConfiguration config = new ClientConfiguration();
  17. config.setProtocol(Protocol.HTTPS);
  18. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, config);
  19. ossClient.putObject(new PutObjectRequest(bucketName, keys, files).withProgressListener(new PutObjectProgressListener(session)));
  20. Date expiration = new Date(System.currentTimeMillis() + EXPIRE_TIME);
  21. URL url = ossClient.generatePresignedUrl(bucketName, keys, expiration);
  22. ossClient.shutdown();
  23. return String.valueOf(url);
  24. } catch (Exception e) {
  25. log.error(e.getMessage(), e);
  26. throw new IllegalStateException("文件上传到阿里云OSS服务报错!", e);
  27. }
  28. }
  29. }

3.5、反射工具

  1. import org.springframework.context.ApplicationContext;
  2. import java.beans.PropertyDescriptor;
  3. import java.lang.reflect.Method;
  4. /** * 反射调用工具类 */
  5. public final class ReflectUtil {
  6. /** * 调用Spring容器中bean的方法 * * @param applicationContext 容器对象 * @param methodDescriptor 方法描述符,类的全限定名#方法名称 * @param parameterTypes 方法参数类型列表 * @param params 方法参数列表 * @param <T> 返回的数据类型 * @return 调用结果 */
  7. public static <T> T invoke(ApplicationContext applicationContext, String methodDescriptor,
  8. Class<?>[] parameterTypes, Object... params) {
  9. String[] array = methodDescriptor.split("#");
  10. Class<?> beanClass = forName(array[0]);
  11. Object bean = applicationContext.getBean(beanClass);
  12. Method method = findMethod(beanClass, array[1], parameterTypes);
  13. return invokeMethod(method, bean, params);
  14. }
  15. /** * 寻找类中的方法 * * @param targetClass 需要查找的类型 * @param methodName 方法名称 * @param parameterTypes 参数类型列表,必须严格一致 * @return 类中的方法 */
  16. public static Method findMethod(Class<?> targetClass, String methodName, Class<?>... parameterTypes) {
  17. try {
  18. Method method = targetClass.getMethod(methodName, parameterTypes);
  19. method.setAccessible(true);
  20. return method;
  21. } catch (Exception e) {
  22. throw new IllegalArgumentException(e);
  23. }
  24. }
  25. /** * 反射调用方法 * * @param method 方法 * @param target 需要调用的对象 * @param parameters 方法参数 * @param <T> 返回的结果类型 * @return 调用结果 */
  26. @SuppressWarnings("unchecked")
  27. public static <T> T invokeMethod(Method method, Object target, Object... parameters) {
  28. try {
  29. return (T) method.invoke(target, parameters);
  30. } catch (Exception e) {
  31. throw new IllegalArgumentException(e);
  32. }
  33. }
  34. /** * 根据类的全限定名获取对应的class对象 * * @param className 类全限定名 * @param <T> 返回的class对象类型 * @return class对象 */
  35. @SuppressWarnings("unchecked")
  36. public static <T> Class<T> forName(String className) {
  37. try {
  38. return (Class<T>) Class.forName(className);
  39. } catch (ClassNotFoundException e) {
  40. throw new IllegalArgumentException(e);
  41. }
  42. }
  43. /** * 调用javaBean的get方法 * * @param target javaBean实体 * @param prop 属性名称 * @param classOfT 该属性对应的类型 * @param <T> 该属性对应的类型 * @return 调用结果 */
  44. @SuppressWarnings("unchecked")
  45. public static <T> T invokeGetter(Object target, String prop, Class<T> classOfT) {
  46. try {
  47. PropertyDescriptor pd = new PropertyDescriptor(prop, target.getClass());
  48. Object value = pd.getReadMethod().invoke(target);
  49. if (value == null) {
  50. return null;
  51. }
  52. if (classOfT.isInstance(value)) {
  53. return (T) value;
  54. } else {
  55. throw new IllegalArgumentException("属性: " + prop + " 的类型不是: " + classOfT);
  56. }
  57. } catch (Exception e) {
  58. throw new IllegalArgumentException(e);
  59. }
  60. }
  61. private ReflectUtil() {
  62. }
  63. }

发表评论

表情:
评论列表 (有 0 条评论,868人围观)

还没有评论,来说两句吧...

相关阅读