In Java, there are two ways to invoke a class's methods: For static methods, you can invoke the class name directly, and you must use the object invocation of the class for non-static methods. The reflection mechanism provides a more alternative way of calling, and you can specify the method you want to invoke without having to be determined programmatically. The method invoked is not limited to public, but can also be private. Write a program that uses the reflection mechanism to call the math class's Static method sin () and non-static method equals ().
The idea is as follows: Use Math.class.getDeclaredMethod ("sin", double.type); Access the specified method where "sin" means the name of the method to be accessed is sin, Double.type indicates that the type of the entry parameter is double.
The code is as follows:
Copy Code code as follows:
Import Java.lang.reflect.Method;
public class Dongtai {
public static void Main (string[] args) {
try {
System.out.println ("Invoke the Static Method sin () of the Math class");
Method sin = Math.class.getDeclaredMethod ("Sin", double.type);
Double sin1 = (double) sin.invoke (null, New Integer (1));
System.out.println ("1 sine value is:" + sin1);
SYSTEM.OUT.PRINTLN ("Call non-static method Equals ()" Of String Class);
Method equals = String.class.getDeclaredMethod ("equals", Object.class);
Boolean Mrsoft = (Boolean) Equals.invoke (New String ("Tomorrow Technology"), "Tomorrow Technology");
System.out.println ("Whether the string is tomorrow Science and Technology:" + Mrsoft);
catch (Exception e) {
E.printstacktrace ();
}
}
}
Effect as shown: