Java reflection mechanism, get objects through class names, and call methods and parameters

Source: Internet
Author: User

Try {// obtain the Class Object Class c = Class. forName ("full class name"); Object yourObj = c. newInstance (); // obtain Method methlist [] = cls. getDeclaredMethods (); for (int I = 0; I <methlist. length; I ++) {Method m = methlist [I];} // obtain the method object. Assume that the Method parameter is an int and the Method name is setAge method sAge = c. getMethod ("setAge", new Class [] {int. class}); // obtain the parameter Object [] arguments = new Object [] {new Integer (37)}; // execute the sAge method. invoke (yourObj, arguments);} catch (Exception e ){}

GetDeclaredMethod * () obtains all methods declared by the class, including public, protected, and private methods.

GetMethod * () obtains all the common methods of the class. This includes all the public methods of the class and all the public methods inherited from the base class and implemented from the interface.


Test example

package com.sf.test;

import java.lang.reflect.Method;

public class RefTest {

public static void main(String args[]) throws Exception { Class clazz = Class.forName("com.sf.test.Test"); Object object = clazz.newInstance(); Method refTest = clazz.getDeclaredMethod("refTest"); Method refTest1 = clazz.getDeclaredMethod("refTest1",String.class); refTest1.invoke(object, "0021212"); refTest.invoke(object); } }


package com.sf.test;

public class Test { public Test(){ } public void refTest() { System.out.println("00000000"); } public void refTest1(String string) { System.out.println(string); }}


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.