java反射--超级好用的方法
1.根据方法名,获取类的对应的方法
Method changeSessionIdMethod = ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId");
if(changeSessionIdMethod == null) {
throw new IllegalStateException("HttpServletRequest.changeSessionId is undefined. Are you using a Servlet 3.1+ environment?");
}
System.out.println(changeSessionIdMethod);
2.休眠当前线程
TimeUnit.MILLISECONDS.sleep(1000);
3. 替换配置文件中特殊的变量将变量中含有 @{test.test} 将变量 test.test 替换为系统中的其他值。
private static final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("@{", "}", ":", false);
private static final PlaceholderResolver placeholderResolver=new PlaceholderResolver(){
@Override
public String resolvePlaceholder(String key) {
return System.getProperty(key);
}
};
4.获取对象的方法名称。dubbo 获取dubbo接口里的方法
String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();
5. {0} 字符串格式化。
String template="test1={0},test2={1},test3={2}";
Object[] objects=new Object[]{0,1,"test2"};
String emailContent = MessageFormat.format(template, objects);
System.out.println(emailContent);
6.spring HiddenHttpMethodFilter 将http里post方法转化为参数里的方法
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { HttpServletRequest requestToUse = request; if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
requestToUse = new HttpMethodRequestWrapper(request, paramValue);
}
} filterChain.doFilter(requestToUse, response);
}
7.判断classpath 中是否存在某个类 原理:先判断是否是基础类型, 再 根据 ClassLoader clToUse = classLoader; (clToUse != null ? clToUse.loadClass(name) : Class.forName(name))
org.springframework.util.ClassUtils
if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
&& !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : WEB_ENVIRONMENT_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
9.获取classpath下的文件,和 jar包里的文件。
public static void main(String[] args) throws Exception {
Enumeration<URL> urls = ClassLoader.getSystemResources("META-INF/services/ch.qos.logback.classic.spi.Configurator");
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
System.out.println(url.getPath());
}
}
// 从url 读取文件内容
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "utf-8"));
10.向目录里写文件,目录和文件不能直接用字符串链接,如目录为:.,文件名为:test.log,直接链接为.log会出错。
public class FileUtil {
public static File getFile(String path,String fileName) throws IOException{
File directory=new File(path);
String filePath=directory.getCanonicalPath();
return new File(filePath+"/"+fileName);
}
}
11.字符串按字节长度截取
public static byte[] subBytes(byte[] src, int begin, int count) {
byte[] bs = new byte[count];
System.arraycopy(src, begin, bs, 0, count);
return bs;
}
if (!StringUtil.isNullOrEmpty(po.getContent())){
byte[] contentB= new byte[0];
try {
contentB = po.getContent().getBytes("utf-8");
if (contentB.length>1024){
po.setContent(new String(StringUtil.subBytes(contentB,0,1024),"utf-8"));
}
} catch (UnsupportedEncodingException e) {
String result="content bytes length > 1024,convert error";
po.setContent(result);
log.error(result,e);
}
}
12.获取类的调用链路
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
java反射--超级好用的方法的更多相关文章
- Java 反射 调用私有域和方法(setAccessible)
Java 反射 调用私有域和方法(setAccessible) @author ixenos AccessibleObject类 Method.Field和Constructor类共同继承了Acces ...
- 【译】7. Java反射——私有字段和私有方法
原文地址:http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html =================== ...
- Java反射理解(五)-- 方法反射的基本操作
Java反射理解(五)-- 方法反射的基本操作 方法的反射 1. 如何获取某个方法 方法的名称和方法的参数列表才能唯一决定某个方法 2. 方法反射的操作 method.invoke(对象,参数列表) ...
- Java反射机制调用对象的方法 —— 将一个对象的属性值赋值给另一个对象的属性
模拟一个场景: 众所周知,EasyExcel导出Excel文档是依赖于注解完成的,在实体类需要导出的属性上面加上注解,导出的时候会自动识别该属性. 假如我们现在需要导出用户的信息,又不想污染原本的实体 ...
- 深入分析Java反射(一)-核心类库和方法
前提 Java反射的API在JavaSE1.7的时候已经基本完善,但是本文编写的时候使用的是Oracle JDK11,因为JDK11对于sun包下的源码也上传了,可以直接通过IDE查看对应的源码和进行 ...
- java反射调用某个对象的方法
// 反射调用某个对象的方法 public Object invokeMethod(Object methodObject, String methodName, Object[] args) thr ...
- Java反射《四》获取方法
package com.study.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.refl ...
- 有关java反射的几个小方法的作用和区别
1.Class类中 getXXX()和getDeclaredXXX()的作用和区别: 前者获取某个类的所有公共(public)的字段(or方法or构造函数),包括父类.后者获取所有的字段(or方法or ...
- 第五课 JAVA反射获取对象属性和方法(通过配置文件)
Service1.java package reflection; public class Service1 { public void doService1(){ System.out.print ...
随机推荐
- Codeforces Round #600 (Div. 2) A. Single Push
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; int T,n ...
- 【Node】Webpack调试启动
"start": "webpack-dev-server --port 33333 --content-base ./dist",
- Microsonf visual c++ 14+ 离线内网安装
内网离线安装方法:先下载官方的visualcppbuildtools: <br href=http://go.microsoft.com/fwlink/?LinkId=691126 >& ...
- OpenCV函数:提取轮廓相关函数使用方法
opencv中提供findContours()函数来寻找图像中物体的轮廓,并结合drawContours()函数将找到的轮廓绘制出.首先看一下findContours(),opencv中提供了两种定义 ...
- spring(三):DefaultListableBeanFactory
- 题解【SP1716】GSS3 - Can you answer these queries III
题目描述 You are given a sequence \(A\) of \(N (N <= 50000)\) integers between \(-10000\) and \(10000 ...
- 转载:EQ
https://blog.csdn.net/qiumingjian/article/details/46326269 https://blog.csdn.net/sszhouplus/article/ ...
- 百炼OJ - 1005 - I Think I Need a Houseboat
题目链接:http://bailian.openjudge.cn/practice/1005/ 思路 一个半圆面积每年增长50,已知一个点坐标,求第几年点在半圆内. #include <stdi ...
- nmon +java nmon Alalizy agent 动态交互监控
下载地址:1. Download and install nmon. - for linux platform, you can download form: http://nmon.sourcefo ...
- c#项目调用Python模块的方法
将Python模块用pyinstaller打包成exe程序 下载安装UPX((http://upx.sourceforge.net/)) ,并把路径加到环境变量中. UPX是开源的加壳和压缩exe的程 ...