Runtime arguments in java

How to get VM arguments from inside of Java application?

I need to check if some option that can be passed to JVM is explicitly set or has its default value. To be more specific: I need to create one specific thread with higher native stack size than the default one, but in case the user wants to take care of such things by himself by specifying the -Xss option I want to create all threads with default stack size (which will be specified by user in -Xss option). I’ve checked classes like java.lang.System and java.lang.Runtime , but these aren’t giving me any useful information about VM arguments. Is there any way to get the information I need?

5 Answers 5

At startup pass this -Dname=value

and then in your code you should use

value=System.getProperty("name"); 

Not sure why this answer has been so upvoted, this only retrieves application parameters (specified with -D), not VM parameters (those specified with -X). The question is specifically about -X params.

I came here because I believed parameters of type -Dname=value are JVM arguments and that there is no intrinsic difference to -X arguments. Actually, they are both passed to java and not the application at the command line and as evidence by example, in maven you can pass both as -Drun.jvmArguments=. . I believe that is why it is upvoted.

Читайте также:  Php функция вызвать класс

Might be ! but it googles on tops when searching for «how to read VM options in code» and that’s why it’s relevant )

With this code you can get the JVM arguments:

import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; . RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); List arguments = runtimeMxBean.getInputArguments(); 

@Daniel, this should get you the name of the main class: final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); final String mainClassName = stackTrace[stackTrace.length — 1].getClassName());

If you are guaranteed to be running on Oracle’s JVM and have the code to parse the arguments that can be useful.

@Vulcan That does not get VM arguments. It contains the main class name, and the args array to the main method.

@dacongy Never did I imply that VM arguments are located in the sun.java.command system property; I said that property can be used to acquire main class name (although I did not mention, as @laz pointed out, that property is only present on Oracle’s JVM).

I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean’s list, you get the full list of arguments.

import java.util.*; import java.lang.management.ManagementFactory; class main < public static void main(final String[] args) < System.out.println(fullVMArguments()); >static String fullVMArguments() < String name = javaVmName(); return (contains(name, "Server") ? "-server " : contains(name, "Client") ? "-client " : "") + joinWithSpace(vmArguments()); >static List vmArguments() < return ManagementFactory.getRuntimeMXBean().getInputArguments(); >static boolean contains(String s, String b) < return s != null && s.indexOf(b) >= 0; > static String javaVmName() < return System.getProperty("java.vm.name"); >static String joinWithSpace(Collection c) < return join(" ", c); >public static String join(String glue, Iterable strings) < if (strings == null) return ""; StringBuilder buf = new StringBuilder(); Iteratori = strings.iterator(); if (i.hasNext()) < buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); >return buf.toString(); > > 

Could be made shorter if you want the arguments in a List .

Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.

Источник

Code example for using command line arguments with Java runtime

System.in compatibility has been confirmed by Stephen C. As an alternative solution, it is recommended to read a set of instructions from an input stream that could be linked to either a Scanner for real-time input or a file for testing at runtime. To execute the commands, it is advisable to create an array list, add the commands, convert them to an array, display the array, and then send the commands.

Executing commands using Java Runtime

To ensure sequential execution of commands, use the Process instance returned by Runtime.exec() and call waitFor() method to wait for completion before moving on to the next command. Communication with the Process can be established using its getInputStream() and getOutputStream() methods.

It is recommended to also go through the Javadoc which explains the behavior of Runtime.exec method. According to the Javadoc, the method executes the specified command string in a distinct process.

  1. It is recommended to utilize Process and ProcessBuilder in place of other options.
  2. The instructions must be segmented and transformed into tokens based on their respective arguments.
  3. The two commands won’t run in the same process with the current way it’s written.
  4. Luckily, with ProcessBuilder , it is possible to modify the command’s working directory.
sendCommand("homepath/plugins", "mvn", "archetype:generate", "-DarchetypeCatalog=file://homepath/.m2/repository"); private static void sendCommand(String workingDirectory, String. command) throws IOException < Process proc = new ProcessBuilder(command).directory(new File(workingDirectory)).start(); int status = proc.waitFor(); if (status != 0) < // Handle non-zero exit code, which means the command failed >> 

Observe the division of the command and the inclusion of the working directory using ProcessBuilder.directory(File) . While this will achieve the desired outcome, it’s important to note that each command will run as a distinct process, and Java cannot combine them. To execute all of the commands simultaneously, you’ll need to utilize Maven’s capabilities and specify multiple build targets.

Command Line Arguments in Java, Java command-line argument is an argument i.e. passed at the time of running the Java program. In the command line, the arguments passed from the console can be received in the java program and they can be used as input. The users can pass the arguments during the execution bypassing the command-line …

Java runtime.getRuntime.exec( cmd ) with long parameters

It’s a good practice to pass the arguments as an array, which deserves a bonus point.

Using a string for all inputs may be successful on certain systems, but it could result in failure on other systems.

Process start = Runtime.getRuntime().exec(new String[] < "java", "-version" >); BufferedReader r = new BufferedReader( new InputStreamReader(start.getErrorStream())); String line = null; while ((line = r.readLine()) != null)

Although you mentioned that you attempted to send the arguments as a String array and it didn’t work, I’m wondering if a different error message appeared. If the other program generates a log, it might be useful to check it out to see what’s causing the issue. To verify the actual input, you might want to create a basic script that prints the parameters it was called with.

Utilize the String[] parameter when invoking ProcessBuilder.

 String[] cmmm = ; ProcessBuilder pb = new ProcessBuilder(cmmm); pb.directory(new File(tDir)); Process p = pb.start(); 

To solve the problem, I opted for an Array and also utilized an ArrayList due to the intricate nature of the commands. After defining the ArrayList, I added the commands, converted it to an Array, displayed it, and sent the commands successfully. It’s important to note that each parameter should be placed in a separate String within the array.

 List list = new ArrayList<>(); list.add("command"); list.add("param"); String[] command = (String[]) list.toArray(new String[0]); log.progress (list); run.exec (command); 

Java Command Line Arguments, Simple example of command-line argument in java In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt. class CommandLineExample < public static void main (String args []) < …

How to add command line parameters when running java code in Eclipse?

In Eclipse, you have the option to define vm arguments while creating a «Run Configuration». To do so, simply navigate to the Arguments tab within the Java Application Run Configuration by right-clicking on your project.

Navigate to the «Run Configurations» menu and then select the «Arguments» option.

Within the Run menu, there is an option called «Run Configurations» that permits the customization of the spawned JVM. The tab labeled «Classpath» enables the setting of the classpath while the other tab, named «Arguments,» allows for the configuration of JVM parameters.

How to Find the Number of Arguments Provided at, Under Java Application –> Click on Arguments. Under Program Arguments, provide the required arguments as specified in the below screen On running the code, we can see below output Example 2: Find out whether “GFG” is provided in the command line arguments Java public class GFG < public static …

Java Eclipse Taking Command Line Arguments Continously in Running Time

Based on this Question in Eclipse, it appears that there are no available options to achieve this. The aforementioned Question also provides some potential solutions. An update has been made to confirm that indeed it is impossible to allocate System.console() .

However, Stephen C has confirmed that it is functional with System.in.

Scanner scanner = new Scanner(System.in); String line; while (true)

It appears that you need to retrieve a series of instructions from an input stream, which could be linked to a Scanner for real-time input or a file for testing purposes during execution.

Источник

Command-Line Arguments

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt , a user would enter:

When an application is launched, the runtime system passes the command-line arguments to the application’s main method via an array of String s. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String : «friends.txt» .

Echoing Command-Line Arguments

The Echo example displays each of its command-line arguments on a line by itself:

The following example shows how a user might run Echo . User input is in italics.

java Echo Drink Hot Java Drink Hot Java

Note that the application displays each word — Drink , Hot , and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink , Hot , and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

java Echo "Drink Hot Java" Drink Hot Java

Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as «34», to a numeric value. Here is a code snippet that converts a command-line argument to an int :

int firstArg; if (args.length > 0) < try < firstArg = Integer.parseInt(args[0]); >catch (NumberFormatException e) < System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); >>

parseInt throws a NumberFormatException if the format of args[0] isn’t valid. All of the Number classes — Integer , Float , Double , and so on — have parseXXX methods that convert a String representing a number to an object of their type.

Источник

Оцените статью