简体   繁体   English

在运行时获取当前的类名

[英]get current class name at runtime

I've two classes: 我有两节课:

public class UThreadApp {
    public static void main(String[] args) {
        newUThread("umain", args);
            ...
    }
    native void newUThread(String method, String[] args);
}

public class App extends UThreadApp {
    public static void umain(String[] args) {
        ...
    }
}

Application is executed as java App . 应用程序作为java App执行。

App inherits main from UThreadApp such that main calls App.umain . App继承了mainUThreadApp ,使得main通话App.umain I've to get programmatically the main class name App from Java or JNI so as to call App.umain from JNI code. 我必须以编程方式从Java或JNI获取主类名称App ,以便从JNI代码调用App.umain Do you see a way to do that? 您看到这样做的方法了吗?

Idioms such that new Object(){}.getClass().getEnclosingClass() don't work since they return UThreadApp . 诸如new Object(){}.getClass().getEnclosingClass() UThreadApp不起作用,因为它们返回了UThreadApp

Static methods have no class, and no this reference. 静态方法没有类,也没有this引用。 Your App class will “inherit” main insofar as that main is usually callable as App.main as well. 您的App类将“继承” main,因为该main通常也可以作为App.main调用。 But you cannot override static methods in the common sense. 但是您不能以常识覆盖静态方法 Once the method got invoked, there is no way to determine what name was used to invoke it. 一旦调用了该方法,就无法确定使用什么名称来调用它。 So nothing you do, on the java side or in native code, will give you the information you desire. 因此,无论是在Java方面还是在本机代码中,任何操作都不会为您提供所需的信息。 Apart from hacking the java executable and figuring out its command line arguments or similar brutal and unsupported approaches, that is. 除了破解Java可执行文件并找出其命令行参数或类似的残酷且不受支持的方法外,这就是事实。

Note: You also have an error where the static main tries to call the non-static newUThread . 注意:在静态main尝试调用非静态newUThread您还会遇到一个错误。

What you could do is something like this, to leave the static scope and get a reasonable this pointer: 您可以执行以下操作,离开static范围并获得合理的this指针:

public class UThreadApp {
    protected void UThreadApp(String[] args) {
        newUThread("umain", args);
            ...
    }
    native void newUThread(String method, String[] args);
}

public class App extends UThreadApp {
    public void main(String[] args) {
        new App(args);
    }
    public App(String[] args) {
        super(args);
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM