Object insecure; //This needs to be an initialized reference
Class c = insecure.getClass();
Method m = c.getMethod(name, parameterTypes); //Fill the name and types in
m.setAccessible(true);
m.invoke(insecure, parameters); //Fill in the parameters you would like
जांचे हुए अपवादों जो फेंक दिया जा सकता है की एक संख्या हैं। पैरामीटर प्रकार और पैरामीटर दोनों लंबवत तर्क (परिवर्तनीय लंबाई) हैं, उन्हें आवश्यकतानुसार भरें। विनिर्देशन द्वारा जेवीएम में दृढ़ता से टाइप किए गए कॉलिंग सम्मेलन हैं, इसलिए आपको पैरामीटर प्रकारों को जानने की आवश्यकता है।
इसके साथ, जब तक कि आप किसी प्रकार के एप्लिकेशन कंटेनर, सर्वर घटक कंटेनर, आरएमआई जैसी प्रणाली, या जेवीएम आधारित लैंगेज लिख रहे हैं, आपको इसे करने से बचना चाहिए। reflection tutorial
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class InvokeMain {
public static void main(String... args) {
try {
Class<?> c = Class.forName(args[0]);
Class[] argTypes = new Class[] { String[].class };
Method main = c.getDeclaredMethod("main", argTypes);
String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
System.out.format("invoking %s.main()%n", c.getName());
main.invoke(null, (Object)mainArgs);
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
} catch (InvocationTargetException x) {
x.printStackTrace();
}
}
}
कोशिश 'MyClass.class.getDeclaredMethod (" MyMethod ", Map.class);' अपने मामले – Cratylus
काफी मजेदार है सामान्य के लिए विधि की जानकारी अभी भी रनटाइम पर उपलब्ध है। 'Method.getGeneric पैरामीटर प्रकार –