品易云推流 关闭
文章详情页
文章 > java基础 > java语言代码大全

java语言代码大全

java语言

头像

小妮浅浅

2021-03-26 10:28:134995浏览 · 0收藏 · 0评论

我们在使用代码的时候,有很多便捷的操作,能够节约编写代码的效率和运行速度,也算是java中的小技巧,下面我们就带来展示。

1、获取要反射的方法

获取反射方法时,有两个方法,getMethod 和 getDeclaredMethod。

class Class {
 @CallerSensitive
 public Method getMethod(String name, Class<?>... parameterTypes)
 throws NoSuchMethodException, SecurityException {
 Objects.requireNonNull(name);
 SecurityManager sm = System.getSecurityManager();
 if (sm != null) {
 // 1. 检查方法权限
 checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
 }
 // 2. 获取方法
 Method method = getMethod0(name, parameterTypes);
 if (method == null) {
 throw new NoSuchMethodException(methodToString(name, parameterTypes));
 }
 // 3. 返回方法的拷贝
 return getReflectionFactory().copyMethod(method);
 }
 @CallerSensitive
 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
 throws NoSuchMethodException, SecurityException {
 Objects.requireNonNull(name);
 SecurityManager sm = System.getSecurityManager();
 if (sm != null) {
 // 1. 检查方法是权限
 checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
 }
 // 2. 获取方法
 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
 if (method == null) {
 throw new NoSuchMethodException(methodToString(name, parameterTypes));
 }
 // 3. 返回方法的拷贝
 return getReflectionFactory().copyMethod(method);
 }
}

2、在Java5中,提供了for-each循环,从而简化了对数组和集合的循环。Fore-each循环允许您遍历数组而不需要保留传统for循环中的索引,也不需要在使用迭代器时调用while循环中的hasNext方法和next方法来遍历集合。

double[] values = ...;
for(double value : values) {
    // TODO: 处理value
}
 
List<Double> valueList = ...;
for(Double value : valueList) {
    // TODO: 处理value
}

3、得到当前方法的名字

<span style=
"font-family:Arial;font-size:14px;"
>String methodName = Thread.currentThread().getStackTrace()[
1
].getMethodName(); </span>

以上就是java语言代码大全,关于这类的Java技巧还有很多,大家在学习的时候要注意总结和归纳。更多Java学习指路:Java基础

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图