Java中的方法类| isVarArgs()方法

这个 JAVA朗,反思 方法isVarArgs() method类的方法检查method对象是否被声明为具有可变数量的参数。如果方法可以接受可变数量的参数,则返回true,否则将返回false。

null

VarArgs(可变长度参数) :

VarArgs允许方法接受多个参数。当不知道要在方法中传递多少个参数时,传递参数比传递数组更好。

语法:

public boolean isVarArgs()

返回值: 当且仅当方法具有可变长度参数else false时,此方法返回true。

下面的程序演示了方法类的isVarArgs()方法:

例1: 下面的程序检查GFG类方法是否有变长参数。在这个程序中,一个方法接受VarArgs,并通过isVarArgs()检查方法是否接受VarArgs,最后打印结果。

// Program Demonstrate isVarArgs() method
// of Method Class.
import java.lang.reflect.Method;
public class GFG {
// create another method
public static void paint(Object... values)
{
String message = "A Computer Science portal for geeks" ;
}
// create main method
public static void main(String args[])
{
try {
// get list of declared method objects of class GFG
Method[] methods = GFG. class .getMethods();
// loop through method list
for (Method method : methods) {
// check method conts VarArgs or not
boolean isVarArgs = method.isVarArgs();
// print result if VarArgs are present
if (isVarArgs)
System.out.println(method + " method accepts VarArgs :"
+ isVarArgs);
}
}
catch (Exception e) {
// Print Exception if any Exception occurs
e.printStackTrace();
}
}
}


输出:

public static void GFG.paint(java.lang.Object[]) method accepts VarArgs :true

例2: 这个程序将返回所有包含java类可变长度参数的方法。util。收藏。

说明:在这个方法中,首先是java。util。集合类对象被创建。在创建java的类对象之后。util。集合类通过调用类对象的getMethods()创建方法对象列表。使用isVarArgs()遍历方法列表并获取包含可变长度参数的方法。最后打印合成方法名称。

// Program Demonstrate isVarArgs() method
// of Method Class.
import java.lang.reflect.Method;
import java.util.Collections;
public class GFG {
// create main method
public static void main(String args[])
{
try {
// create class object for class Collections
Class c = Collections. class ;
// get list of Method object
Method[] methods = c.getMethods();
System.out.println( "Methods of Collections Class"
+ " contains VarArgs" );
// Loop through Methods list
for (Method m : methods) {
// check whether the method  contains VarArgs or not
if (m.isVarArgs())
// Print Method name
System.out.println( "Method: " + m.getName());
}
}
catch (Exception e) {
// print Exception is any Exception occurs
e.printStackTrace();
}
}
}


输出:

Methods of Collections Class contains VarArgs
Method: addAll

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享