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反射--超级好用的方法的更多相关文章

  1. Java 反射 调用私有域和方法(setAccessible)

    Java 反射 调用私有域和方法(setAccessible) @author ixenos AccessibleObject类 Method.Field和Constructor类共同继承了Acces ...

  2. 【译】7. Java反射——私有字段和私有方法

    原文地址:http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html =================== ...

  3. Java反射理解(五)-- 方法反射的基本操作

    Java反射理解(五)-- 方法反射的基本操作 方法的反射 1. 如何获取某个方法 方法的名称和方法的参数列表才能唯一决定某个方法 2. 方法反射的操作 method.invoke(对象,参数列表) ...

  4. Java反射机制调用对象的方法 —— 将一个对象的属性值赋值给另一个对象的属性

    模拟一个场景: 众所周知,EasyExcel导出Excel文档是依赖于注解完成的,在实体类需要导出的属性上面加上注解,导出的时候会自动识别该属性. 假如我们现在需要导出用户的信息,又不想污染原本的实体 ...

  5. 深入分析Java反射(一)-核心类库和方法

    前提 Java反射的API在JavaSE1.7的时候已经基本完善,但是本文编写的时候使用的是Oracle JDK11,因为JDK11对于sun包下的源码也上传了,可以直接通过IDE查看对应的源码和进行 ...

  6. java反射调用某个对象的方法

    // 反射调用某个对象的方法 public Object invokeMethod(Object methodObject, String methodName, Object[] args) thr ...

  7. Java反射《四》获取方法

    package com.study.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.refl ...

  8. 有关java反射的几个小方法的作用和区别

    1.Class类中 getXXX()和getDeclaredXXX()的作用和区别: 前者获取某个类的所有公共(public)的字段(or方法or构造函数),包括父类.后者获取所有的字段(or方法or ...

  9. 第五课 JAVA反射获取对象属性和方法(通过配置文件)

    Service1.java package reflection; public class Service1 { public void doService1(){ System.out.print ...

随机推荐

  1. mybatis(五):源码分析 - 参数映射流程

  2. 使用Python发送、订阅消息

    使用Python发送.订阅消息 使用插件 paho-mqtt 官方文档:http://shaocheng.li/post/blog/2017-05-23 Paho 是一个开源的 MQTT 客户端项目, ...

  3. [POI2000] 公共串 - 后缀数组,二分

    [POI2000] 公共串 Description 给出几个由小写字母构成的单词,求它们最长的公共子串的长度. Solution 预处理出后缀数组和高度数组,二分答案 \(k\) ,对于每一个连续的 ...

  4. 0215 docker环境

    docker的下载安装和基本使用 我使用的mac,直接安装desktop. 然后命令行使用docker,关于desktop的使用,可以看官方文档. 安装好之后,确认一下是否可以运行,输入docker ...

  5. Java+Selenium+Testng自动化测试学习(三)— 断言

    1.修改Login类加入断言: 断言:检查我们操作页面后得到的结果与我们预期的结果是否一致. 2.使用xml文件运行所有的测试类: Login类写入两个测试用例: package com.test; ...

  6. 基于Docker的Mysql Cluster集群

    参考 mysql-cluster镜像 https://medium.com/@ahmedamedy/mysql-clustering-with-docker-611dc28b8db7 使用Docker ...

  7. 【C语言】复合函数求值

    例子:求复合函数F(G(X)),其中F(x)=|x-3|+|x+1|,函数G(x)=x^2-3x. 分析:从复合函数的结构可以看出,F函数的自变量为G函数的绝对值,可以将F函数和G函数作为独立的函数实 ...

  8. html代码分享

    贴图:<img src="图片URL"> 加入连接:<a href="所要连接的相关URL">写上你想写的字</a> 在新窗 ...

  9. RTMP服务器搭建(nginx+rtmp)

    参考文章:https://obsproject.com/forum/resources/how-to-set-up-your-own-private-rtmp-server-using-nginx.5 ...

  10. C#中数据类型char*,const char*和string的三者转换

    C#中数据类型char*,const char*和string的三者转换: . const char* 和string 转换 () const char*转换为 string,直接赋值即可. EX: ...