简体   繁体   English

在Java中使用变量调用类和方法

[英]Invoking a Class and Method Using Variables In Java

I am attempting to call a custom class and method on my Application start-up to perform dev testing. 我试图在我的应用程序启动时调用自定义类和方法来执行开发测试。 I have stored the setting for my test class and method in my SettingsClass as shown below. 我将测试类和方法的设置存储在SettingsClass中,如下所示。

public class SettingsClass {

        public static final boolean BOOT_TEST = true;
        public static final String BOOT_CLASS = "MyClass";
        public static final String BOOT_METHOD = "MyMethod";

    }

My Main Class. 我的主要课程。

public class MainClass {


        public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {

            if(SettingsClass.BOOT_TEST) {
                Method method = getDeclaredMethodClass(SettingsClass.BOOT_CLASS).getDeclaredMethod(SettingsClass.BOOT_METHOD);
                method.invoke();
                System.exit(1);
            }
}

Is it possible to perform the above action? 是否可以执行上述操作?

Any help would be appreciated. 任何帮助,将不胜感激。

You need both a reference to the Class type and an instance of the class (unless the method you want to invoke is static). 您需要对Class类型的引用和类的实例(除非您要调用的方法是静态的)。 In your pseudo code you have the correct idea, all you need to do is a quick review of the javadoc for java.lang.Class and java.lang.reflect.Method 在您的伪代码中,您有正确的想法,您需要做的就是快速查看java.lang.Classjava.lang.reflect.Method的javadoc。

public class SettingsClass {

    public static final boolean BOOT_TEST = true;
    public static final String BOOT_CLASS = "MyClass";
    public static final String BOOT_METHOD = "doMain";

}

public class MyClass {
    public static void doMain() {
    }
}

public class MainClass {


    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {

        if(SettingsClass.BOOT_TEST) {
            Class<?> clazz = Class.forName(SettingsClass.BOOT_CLASS);
            Method m = clazz.getMethod(SettingsClass.BOOT_METHOD);
            m.invoke(null);
            System.exit(1);
        }

} }

for .invoke() you need an object that is an instance of your class. 对于.invoke(),您需要一个对象,该对象是您的类的实例。

if your class has an public default consturctor you should be able to do something like this 如果你的类有一个公共默认的consturctor你应该能够做这样的事情

// load your class
Class<?> clazz = Class.forName("full.package.and.class.name"); 
// get the method
Method method = clazz.getDeclaredMethod("methodName");
// create an instance of your class
Object object = clazz.newInstance();
// call the method in context of object
method.invoke(object);

You can refer to Java reflection (Method Invocation) 你可以参考Java 反射 (方法调用)

http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html

you can find methods through 你可以通过找到方法

Class<?> c = Class.forName("nameClass");
Object t = c.newInstance();

Method[] allMethods = c.getDeclaredMethods();

and you can call through 你可以打电话给

m.setAccessible(true);
Object o = m.invoke(t, .... ) 

Yes, it is. 是的。 The following code will execute the method someMethod in the MainClass . 以下代码将执行MainClass someMethod方法。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainClass {

  public static final boolean BOOT_TEST = true;
  public static final String BOOT_CLASS = "MainClass";
  public static final String BOOT_METHOD = "someMethod";

  public static void main(String[] args) throws InstantiationException,
      IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

    if (MainClass.BOOT_TEST) {
      Class bootClass = Class.forName(BOOT_CLASS);
      Method bootMethod = bootClass.getDeclaredMethod(BOOT_METHOD, null);
      bootMethod.invoke(null, null);
    }
  }

  public static void someMethod() {
    System.out.println("Some method executing...");
  }
}

What you need to do is get the class object for the class whose method you wish to execute dynamically by using the static method Class.forName(String) passing in the class's name. 您需要做的是通过使用传入类名的静态方法Class.forName(String)要动态执行其方法的类的类对象。 subsequently you can request the method you wish to execute using the getDeclaredMethod(String, Class<?>...) passing in the method's name and parameter types. 随后,您可以使用getDeclaredMethod(String, Class<?>...)传入方法的名称和参数类型getDeclaredMethod(String, Class<?>...)以请求要执行的方法。 Following that you can call invoke(Object, Object...) on the method with two null arguments (execute the method on no instance of the class (static execution) without any parameters). 接下来,您可以使用两个空参数在方法上调用invoke(Object, Object...) (在没有任何参数的类的任何实例上执行该方法(静态执行))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用java反射调用匿名类的方法时访问异常 - access exception when invoking method of an anonymous class using java reflection 实例化一个对象并使用JAVA中的反射通过.class文件调用方法? - instantiate an object and invoking a method via a .class file using reflection in JAVA? 在Java中使用反射调用方法 - Invoking a method using reflection in Java 从 Java 中的 class 外部调用的私有方法 - Private method invoking from outside the class in Java 在Java中调用没有反射的匿名类的方法 - Invoking a method of an anonymous class without reflection in java 引用参考文献class中的数组变量,用另一种方法排序,在case语句中调用排序后的值 - Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement 使用MEL调用Java有效负载的方法 - Invoking method on java payload using MEL 使用 java 反射调用 setter 方法 - Invoking setter method using java reflection 使用反射从Scala调用Java类 - Invoking java class from scala using reflection 在java中“用类名调用静态方法”和“用对象调用静态方法”之间有什么区别吗? - is there any difference between “invoking a static method with class name” and “invoking a static method with an object” in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM