Java dynamically invokes the method code in the class

  • 2020-04-01 02:59:35
  • OfStack

In Java, there are two ways to invoke methods of a class: static methods can be invoked directly using the class name, and non-static methods must be invoked using the class's object. Reflection provides a more alternative way to invoke a method that can be specified as needed without having to be determined programmatically. The methods invoked are not limited to public, they can also be private. Write a program that USES reflection to call the static method sin() and non-static equals() of the Math class.

Thinking is as follows: using Math. Class. GetDeclaredMethod (" sin ", Double. TYPE); Access the specified method, where "sin" means the name of the method to be accessed is sin, and Double.TYPE means the TYPE of the entry parameter is Double.

The code is as follows:


import java.lang.reflect.Method; 

public class DongTai { 
    public static void main(String[] args) { 
        try { 
            System.out.println(" call Math class sin()"); 
            Method sin = Math.class.getDeclaredMethod("sin", Double.TYPE); 
            Double sin1 = (Double) sin.invoke(null, new Integer(1)); 
            System.out.println("1 The sine value of " + sin1); 
            System.out.println(" call String class equals()"); 
            Method equals = String.class.getDeclaredMethod("equals", Object.class); 
            Boolean mrsoft = (Boolean) equals.invoke(new String(" Tomorrow's science and technology "), " Tomorrow's science and technology "); 
            System.out.println(" String is tomorrow's technology: " + mrsoft); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
} 

The effect is as follows:

< img border = 0 SRC = "/ / img.jbzj.com/file_images/article/201402/2014224155951569.png" >


Related articles: