温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java语言中一些方法技巧

发布时间:2021-05-06 13:44:18 来源:亿速云 阅读:106 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关java语言中一些方法技巧,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

Java有哪些集合类

Java中的集合主要分为四类:1、List列表:有序的,可重复的;2、Queue队列:有序,可重复的;3、Set集合:不可重复;4、Map映射:无序,键唯一,值不唯一。

我们在使用代码的时候,有很多便捷的操作,能够节约编写代码的效率和运行速度,也算是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语言中一些方法技巧”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI