The difference between GetMethods and getdeclaredmethods in reflection

Source: Internet
Author: User



Public method[] GetMethods () returns all public methods of a class, including the common methods of its inheriting classes, and, of course, the methods of the interfaces it implements.
Public method[] The Getdeclaredmethods () object represents all of the methods declared by the class or interface, including common, protected, default (package) access, and private methods, but does not include inherited methods. Of course, it also includes the method of the interface it implements.





public static void main (String [] args) throws ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
         Bean bean = new Bean ("QQ", 18);
         System.out.println (bean);

         // use reflection
         String className = "com.my.test.Bean";
        
         Class <Bean> clas = (Class <Bean>) Class.forName (className); 

         // Generate an instance
         Bean b = (Bean) clas.newInstance ();
         b.setAge (20);
         b.setName ("WW");
         System.out.println (b);
        
         // call method
         clas.getMethod ("setName", String.class) .invoke (bean, "Jerry");
         clas.getMethod ("setAge", int.class) .invoke (bean, 25);
         System.out.println ("After reflection .... \ n" + bean);
     } 





Example of a dynamic execution method for "Go" using reflection:\

Java uses reflection to dynamically execute class methods
Person class
public class Person {
String name;
String day;
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getDay () {
return day;
}
public void setDay (String day) {
this.day = day;
}
public void printlinfo () throws RuntimeException, IOException {
System.out.println (name);
System.out.println (day);
String url = "http://www.163.com";
   openURL (url);

}
public void openURL (String url) throws RuntimeException, IOException {
String urlx = null;
urlx = "rundll32 url.dll, FileProtocolHandler" + url;


Process p = Runtime.getRuntime (). Exec ("" + urlx);

}

}




Use methods that reflect dynamic execution classes
public static void print (byte [] b1, String tname, String tday) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
    
    MyClassLoade myClassLoader = new MyClassLoade ();
        Class c = myClassLoader.defineClass ("Person", b1);
        System.out.println (c.getName ());
        Object object = c.newInstance ();
        Field [] fields = c.getDeclaredFields ();
        System.out.println (fields.length);
        String args = "java.lang.String";
        Method method1 = c.getDeclaredMethod ("setName", args.getClass ());
        method1.invoke (object, new Object [] {tname});
        Method method2 = c.getDeclaredMethod ("setDay", args.getClass ());
        method2.invoke (object, new Object [] {tday});
            Method method = c.getDeclaredMethod ("printlinfo", null);
        method.invoke (object);
    
    }


Reference: Using reflection to realize automatic assignment of JavaBean
import java.lang.reflect.Method;
import java.util. *;
import javax.servlet.http.HttpServletRequest;
import com.sns.exception.ApplicationException;
public final class ParameterUtil {
public static void setFormBean (HttpServletRequest request, Object bean) {
Class c = bean.getClass ();
Method [] ms = c.getMethods ();
for (int i = 0; i <ms.length; i ++) {
    String name = ms.getName ();
    if (name.startsWith ("set")) {
     Class [] cc = ms.getParameterTypes ();
     if (cc.length == 1) {
      String type = cc [0] .getName (); // parameter type
      try {
        // get property name:
        String prop = Character.toLowerCase (name.charAt (3)) + name.substring (4);
        // get parameter value:
        String param = getString (request, prop);
        if (param! = null &&! param.equals ("")) {
         //ms.setAccessible(true);
         if (type.equals ("java.lang.String")) {
          ms.invoke (bean, new Object [] {param});
         }
         else if (type.equals ("int") || type.equals ("java.lang.Integer")) {
          ms.invoke (bean, new Object [] {new Integer (param)});
         }
         else if (type.equals ("long") || type.equals ("java.lang.Long")) {
          ms.invoke (bean, new Object [] {new Long (param)});
         }
         else if (type.equals ("boolean") || type.equals ("java.lang.Boolean")) {
          ms.invoke (bean, new Object [] {Boolean.valueOf (param)});
         }
         else if (type.equals ("java.util.Date")) {
          Date date = DateUtil.parseDateTime (param);
          if (date! = null)
            ms.invoke (bean, new Object [] {date});
         }
        }
      }
      catch (Exception e) {
        e.printStackTrace ();
      }
     }
    }
}
}
}
Whenever the setXxx () method in JavaBean is found, the corresponding field xxx of the form is automatically found. If found, this method is called using reflection to assign the corresponding field value to JavaBean.
Since the variable names and values passed by the form are all strings, some conversion is required. Currently, the data types that the program can handle include: boolean, Boolean, int, Integer, long, Long, Date, and unsupported data types are automatically ignored. You can also easily add new types.
Please note that only public set methods can be called. If you want the private or protected set methods to be called, please change the red marked getMethods () to getDeclaredMethods () to get all methods including private and protected, and set ms.setAccessible (true); Comments are removed so that private and protected methods can be called correctly.
Reflection is a very powerful function of the Java language, but because reflection will destroy the object encapsulation, and the speed of the reflection call is slow, it can only be used in the necessary tool classes.
#Java

The difference between GetMethods and getdeclaredmethods in reflection


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.