Method code _java in Java dynamic invocation class

Source: Internet
Author: User
Tags reflection sin

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.