advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 4/5 | Rate this item | 1 user has rated this item.
Expertise: Advanced
Language: Java
June 17, 2008
Obtain Class Methods Using Reflection
In this example, you will obtain all methods, all declared methods, and one specific method for the java.lang.reflect.Method class:

import java.lang.reflect.*;
public class getMethodsWithReflection {
public static void main(String[] args){
Class getclass=null;
try{
//indicate the class name
getclass = Class.forName("java.lang.reflect.Method");
}catch(java.lang.ClassNotFoundException e)
{System.out.println(e.getMessage());
}
//get all methods
Method[] methods=getclass.getMethods();
System.out.println("Get all methods:\n");
for (int i=0; i<methods.length; i++)
System.out.println(methods[i]);
//get the declared methods
System.out.println("\nGet declared methods:\n");
methods=getclass.getDeclaredMethods();
for (int i=0; i<methods.length; i++)
System.out.println(methods[i]);
// get a specified method
System.out.println("\nGet a specified method:\n");
try{
Method method = getclass.getMethod("getExceptionTypes",
new Class[] {});
System.out.println(method);
}catch (NoSuchMethodException e)
{System.out.println(e.getMessage());}
}
}
Leonard Anghel
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement