简体   繁体   English

用于独立执行并作为jar库的Java应用程序

[英]java application for stand alone execution and as a jar library

I want to create a java application that can be executed in two ways. 我想创建一个可以以两种方式执行的Java应用程序。 As a standard stand alone application, using main(args[]), and with in any java application using a jar, imported to that other application as an external library. 作为标准的独立应用程序,请使用main(args []),并在任何使用jar的Java应用程序中将其作为外部库导入到其他应用程序。

The problem i am facing is that i want to use the same function on both cases. 我面临的问题是我想在两种情况下使用相同的功能。 This is causing be error, since i have to declare static the methods and variables when executed as stand alone application but as not static when i need to access it from an other application. 这导致了错误,因为当我作为独立应用程序执行时,我必须声明静态方法和变量,但是当我需要从其他应用程序访问它时,则必须声明为静态。

I have never done that before, so i am not 100% sure that this is a real problem. 我以前从未做过,所以我不是100%确定这是一个真正的问题。 my past projects were always static all the way. 我过去的项目一直都是静态的。 I am guessing i could bread my code in two classes, having the main on one and every other method on the other and use it as it was a separate project. 我猜我可以将我的代码放在两个类中,将主代码放在一个方法上,将每个其他方法放在另一个方法上,并使用它,因为它是一个单独的项目。 Is this a correct approach? 这是正确的方法吗?

Try writing it like this: 尝试这样写:

public class DoubleDuty {
    // This is the main method executed using java -jar
    public static void main(String [] args) {
        DoubleDuty dd = new DoubleDuty();
        dd.complexApplication();
    }

    public void complexApplication() {
        // This can be executed by others who import this JAR.
    }
}

only one public static main() is necessary in you new class. 新类中仅需要一个公共static main()。

The main is always static, but you class can have instances. main始终是静态的,但是您的类可以具有实例。

You can call it by another class: 您可以通过另一个类来调用它:

public class Class1 {
public static void main(String args[])
    {
    System.out.println("Class1 BEGINS !");
    }
}

public class Class2 {
    public static void main(String args[])
        {
        Class1.main(args);
        // or that
        Class1.main(new String[0]); beware if inside main , you read args !
        }

} }

when you compile your jar as standalone, set the start to the other class: Lauch Configuration => set Class1 or Class2 当您将jar编译为独立时,请将开始设置为另一个类:Lauch Configuration => set Class1或Class2

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

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