Java 中的 getParameterTypes()、getGenericParameterTypes()方法

Method Class | getParameterTypes() Method in Java - GeeksforGeeks

先决条件:Java 中的 Java.lang.Class 类 |集1、Java中的Java.lang.Class类|套装2 

java.lang.reflectMethod 类帮助我们获取类或接口上单个方法的信息。该类还提供对类方法的访问并在运行时调用它们。

Method 类的 getParameterTypes() 方法: 
对于创建方法,很多时候需要参数才能使这些方法正常工作。 Method 类的 getParameterTypes() 方法返回一个 Class 对象数组,该数组表示编码时在方法中声明的参数类型。如果方法对象不带参数,则 getParameterTypes() 返回长度为 0 的数组。

句法:

public Class[] getParameterTypes()

参数:该方法不带任何参数。

返回值:该方法返回一个 Class 对象数组,该数组按声明顺序表示方法对象的形式参数类型。

下面的程序说明了 Method 类的 getParameterTypes() 方法:

程序 1:下面的程序将打印 Class 对象数组的详细信息,这些对象表示程序中定义的方法对象的形式参数类型。

 

/*
* Program Demonstrate how to apply getParameterTypes() method
* of Method Class.
*/
import java.lang.reflect.Method;
public class GFG {
 
    // Main method
    public static void main(String[] args)
    {
        try {
            // Create class object
            Class classobj = GFG.class;
 
            // Get Method Object
            Method[] methods = classobj.getMethods();
 
            // Iterate through methods
            for (Method method : methods) {
 
                // We are only taking method defined in the demo class
                // We are not taking other methods of the object class
                if (method.getName().equals("setValue")
                    || method.getName().equals("getValue")
                    || method.getName().equals("setManyValues")) {
                    // Apply getParameterTypes() method
                    Class[] parameters = method.getParameterTypes();
 
                    // Print parameter Types of method Object
                    System.out.println("\nMethod Name : "
                                       + method.getName());
                    System.out.println("No of Parameters : "
                                       + parameters.length);
                    System.out.println("Parameter object details:");
                    for (Class classobject : parameters) {
                        System.out.println(classobject.getName());
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    // Method containing two parameter
    public void setValue(String value1, String value2)
    {
        System.out.println("setValue");
    }
 
    // Method containing no parameter
    public String getValue()
    {
        System.out.println("getValue");
        return "getValue";
    }
 
    // Method containing many parameter
    public void setManyValues(int value1, double value2, String value3)
    {
        System.out.println("setManyValues");
    }
}
输出:
Method Name : setManyValues
No of Parameters : 3
Parameter object details:
int
double
java.lang.String

Method Name : getValue
No of Parameters : 0
Parameter object details:

Method Name : setValue
No of Parameters : 2
Parameter object details:
java.lang.String
java.lang.String

程序 2:我们给出一个参数类对象作为输入,如果方法对象包含参数,下面的程序将计算这些类型参数的数量,否则程序返回 0。

 

/*
* Program Demonstrate how to apply getParameterTypes() method
* of Method Class.
*/
import java.lang.reflect.Method;
import java.lang.reflect.Type;
 
public class GFG3 {
 
    // Main method
    public static void main(String[] args)
    {
        try {
            // Create class object
            Class classobj = sample.class;
 
            Method[] methods = classobj.getMethods();
 
            /* Check whether setManyValues() method contains
                        int parameter or not
                and print no of string parameter it contains*/
 
            for (Method method : methods) {
                if (method.getName().equals("setValue")) {
                    int count = containsParameter(method,
                               (Class)java.lang.String.class);
                    System.out.println("No of String "+
                        "Parameters in setValue(): " + count);
                }
            }
 
            /* Check whether setManyValues() method contains
                        int parameter or not
            and print no of string parameter it contains */
 
            for (Method method : methods) {
                if (method.getName().equals("setManyValues")) {
                    int count = containsParameter(method,
                                            (Class) int.class);
                    System.out.println("No of int Parameters"+
                             " in setManyValues(): " + count);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    // Count no of parameters contain by method same as passed to method
    private static int containsParameter(Method method, Class parameterName)
    {
        int count = 0;
 
        // Get all parameter class objects  using getParameterTypes()
        Class parameters[] = method.getParameterTypes();
 
        for (int i = 0; i < parameters.length; i++) {
            // Check contains parameter or not
            if (parameters[i] == parameterName) {
                count++;
            }
        }
 
        return count;
    }
}
// A simple class
class sample {
 
    // Method containing two parameter
    public void setValue(String value1, String value2)
    {
        System.out.println("setValue");
    }
 
    // Method containing many parameter
    public void setManyValues(int value1, double value2, String value3)
    {
        System.out.println("setManyValues");
    }
}
输出:
No of String Parameters in setValue(): 2
No of int Parameters in setManyValues(): 1

参考: getParameterTypes() 的 Oracle 文档 Oracle Doc for getParameterTypes()

java.lang.reflect.Method 类的 Method.getGenericParameterTypes() 方法返回一个 Type 对象数组,这些对象表示在编码时在方法中声明的参数类型。这意味着 getGenericParameterTypes() 方法返回属于方法对象的参数数组。
如果方法对象不带任何参数,则返回长度为 0 的数组。

如果形式参数类型是参数化类型,则为其返回的 Type 对象必须准确反映源代码中使用的实际类型参数。
例如,对于 public 方法,void getValue(T value){} 将类型参数 T 替换为参数化类型(即 List),然后方法将返回“java.util.List”作为参数类型。

语法:

public Type[] getGenericParameterTypes()

返回值:此方法返回一个 Types 数组,该数组按声明顺序表示方法对象的形式参数类型。

例外:此方法引发以下异常:

    • GenericSignatureFormatError – 如果泛型方法签名与 JVM 规范中指定的格式不同。
    • TypeNotPresentException – 如果参数类型引用不存在的类型声明。
    • MalformedParameterizedTypeException – 如果基础参数类型引用由于任何原因无法实例化的参数化类型。

下面的程序说明了 Method 类的 getGenericParameterTypes() 方法:

节目一:打印为方法声明的所有参数类型

 

// Program Demonstrate how to apply getGenericParameterTypes() method
// of Method Class.
  
import java.lang.reflect.Method;
import java.lang.reflect.Type;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
        try {
            // create class object
            Class classobj = demoClass.class;
  
            // get Method Object
            Method[] methods = classobj.getMethods();
  
            // iterate through methods
            for (Method method : methods) {
  
                // only taking method defined in the demo class
                if (method.getName().equals("setValue")
                    || method.getName().equals("getValue")
                    || method.getName().equals("setManyValues")) {
  
                    // apply getGenericParameterTypes() method
                    Type[] parameters = method.getGenericParameterTypes();
  
                    // print parameter Types of method Object
                    System.out.println("\nMethod Name : "
                                       + method.getName());
                    System.out.println("No of Parameters : "
                                       + parameters.length);
                    System.out.println("Parameter object details:");
                    for (Type type : parameters) {
  
                        System.out.println(type.getTypeName());
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
// a simple class
class demoClass {
  
    // method containing two parameter
    public void setValue(String value1, String value2)
    {
        System.out.println("setValue");
    }
  
    // method containing no parameter
    public String getValue()
    {
        System.out.println("getValue");
        return "getValue";
    }
  
    // method containing many parameter
    public void setManyValues(int value1,
                              double value2,
                              String value3)
    {
        System.out.println("setManyValues");
    }
}
输出:
Method Name : setManyValues
No of Parameters : 3
Parameter object details:
int
double
java.lang.String

Method Name : getValue
No of Parameters : 0
Parameter object details:

Method Name : setValue
No of Parameters : 2
Parameter object details:
java.lang.String
java.lang.String

节目二:检查 Method 对象是否包含参数

 

// Program Demonstrate how to apply getGenericParameterTypes()
// method of Method Class.
import java.lang.reflect.Method;
import java.lang.reflect.Type;
  
public class GFG {
  
    // Main method
    public static void main(String[] args)
    {
        try {
            // create class object
            Class classobj = sample.class;
  
            Method[] methods = classobj.getMethods();
  
            /*check whether setManyValues() method contains 
                         int parameter or not
                and print no of string parameter it contains*/
  
            for (Method method : methods) {
                if (method.getName().equals("setValue")) {
  
                    int count = containsParameter(
                        method,
                        (Type)java.lang.String.class);
                    System.out.println("No of String"
                                       + " Parameters in setValue(): "
                                       + count);
                }
            }
  
            // check whether setManyValues() method
            // contains int parameter or not
            // and print no of string parameter it contains
  
            for (Method method : methods) {
  
                if (method.getName().equals("setManyValues")) {
  
                    int count = containsParameter(method,
                                                  (Type) int.class);
  
                    System.out.println("No of int Parameters"
                                       + " in setManyValues(): "
                                       + count);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
  
    // count no of parameters contain by
    // method same as passed to method
    private static int
    containsParameter(Method method,
                      Type parameterName)
    {
        int count = 0;
  
        // get all parameter types list
        // using getGenericParameterTypes()
        Type parameters[] = method.getGenericParameterTypes();
  
        for (int i = 0; i < parameters.length; i++) {
            // check contains parameter or not
            if (parameters[i] == parameterName) {
                count++;
            }
        }
  
        return count;
    }
}
// a simple class
class sample {
  
    // method containing two parameter
    public void setValue(String value1,
                         String value2)
    {
        System.out.println("setValue");
    }
  
    // method containing many parameter
    public void setManyValues(int value1,
                              double value2,
                              String value3)
    {
        System.out.println("setManyValues");
    }
}
输出:
No of String Parameters in setValue(): 2
No of int Parameters in setManyValues(): 1

参考资料: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getGenericParameterTypes–

 

posted @ 2024-06-28 14:26  CharyGao  阅读(65)  评论(0编辑  收藏  举报