Can we execute a program without main method and how in java tell me any example. have you done that kind of example.
Yes, it's possible:
public class MyClass {
static {
Runnable r = new Runnable() {
public void run() {
// whatever you like
}
};
Thread t = new Thread(r)
t.start();
t.join();
}
}
Now you run java passing this class to the command. Java loads the class before attempting to run its main (which doesn't exist), but in loading the class, it fires the static block, which halts until the thread finishes.
If the thread finishes without exiting, java will complain there's no main method, but by that time the thread could have run anything for any duration.
You'll have to catch some exceptions in there, but it will work.
public class TestWithoutMain {
// static block executes first
static{
System.out.println("Program without main");
System.exit(0);
}
}
Note : This works well in JDK1.7 old versions(build 1.7.0-ea-b19)
from jdk 1.7(build1.7.0-ea-b85),It gives run time Exception
Yes, sequence is as follows:
jvm loads class
executes static blocks
looks for main method and invokes it
So, if there's code in a static block, it will be executed. But there's no point in doing that.
How to test that:
public final class Test {
static {
System.out.println("FOO");
}
}
Then if you try to run the class (either form command line with java Test or with an IDE), the result is:
Error will be this.
FOO
java.lang.NoSuchMethodError: main
and ans is that no you can not execute program without main method but the thing is that u can use it either way means partial.
and how ever you can achieve by using static block like this.
static{
System.out.println("Program without main executing into the environment.");
System.exit(0);
}
In Java 9 and beyond you can use JShell to execute Java code without requiring a main method. Not suitable for a stand alone application, but great for quickly testing your code and prototyping changes.
Unless its is web application, I don't think that is possible for any stand alone application which is being self executable, the Runtime should know the entry point, The runtime design such a way that main method is an entry point.
Related
I have a simple restarting Runnable:
static void launchThreads(){
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
try {
exec.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
try {
System.out.println("line"); <--breakpoint
}
catch (Exception e) {
e.printStackTrace(); <--breakpoint
}
}
}, 1, 1000, TimeUnit.MILLISECONDS);
}catch (Exception e) {
e.printStackTrace(); <--breakpoint
}
}
If I launch that method from the main() method of the class, it works as expected - writes a line that looks like "line", once a second, forever.
line
line
line
line
...
But if I launch that from a TestNG test method:
#Test
public class PostpackagesIntegratorTest {
#Test
public void testLaunchThreads10SmallestWithoutFees() {
PostpackagesIntegrator.launchThreads();
}
}
,it outputs only one "line" and the test is passed. "Successfully".
If I make a JUnit4 test to launch the same method,
public class PostpackagesIntegratorJUnit4Test {
#Test
public void launchThreadsTest() {
PostpackagesIntegrator.launchThreads();
}
}
, the test is also passed, again with only one "line" in output.
If I am not running, but debugging the tests, my IntelliJ stops at printing the "line", but does not notice any catch content.
I do not understand, what prevents the ScheduledExecutorService from repetitions. According to docs, such non-repeating should happen at an exception, but no exception happens.
Is it possible to make ScheduledExecutorService in TestNG tests or must I use other classes? Due to the whole project, I am limited by Java 6 version and TestNG.
Edit: #Eugene advised to declare exec as private static final ScheduledExecutorService exec, for blocking erroneous GC, but it did not help and even didn't change anything - the problem is elsewhere.
I would start by dumping a lot of thread details.
Thread.currentThread().dumpStack() (or just (new Throwable()).printStackTrace()) would show any peculiar classes frames above your runnable. These could be quite different if junit/ng are fiddling with thread factories or such.
Then you can also inspect the thread.currentThread() for isDaemon() and the threadgroup's isDeamon(). Your new executorsvc may be part (and making worker threads in) a threadgroup that is interrupted. You might be able to reveal that by writing your own thread factory and issuing threads whose interrupt() is proxied for the sake of trapping it (before forwarding it). A main() is normally a non-daemon thread, so it would spawn non daemon threads too for the execsvc. I wouldn't be surprised is junit/ng are wrapping the test in a pseudo thread sandbox to 'try' to detect and perhaps stop leaked/forgotten threads from a test.
If your are in a debugger, you should be able to browse the top frame local variables and the thread instance already without much code, to reveal all of the above (except the unanticipated interrupt call, if any).
In my java code there is class A that has the following line:
Process localProcess = Runtime.getRuntime().exec(myString);
where myString is user supplied input and is passed to exec() at runtime.
Also there is a public method doSomething() in class A.
Can I somehow invoke doSomething() (through reflection, jdwp etc.) using exec() at runtime ?
Starting a new JVM just to call a single method? First, that would be really slow. And second, it would be highly unnecessary!
Reflection is what you want I guess. Here's some sample code.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Class<Main> c = Main.class; // First get the class
try {
Method method = c.getMethod("doSomething"); // get the method by its name
method.invoke(new Main()); // call it on a new instance of Main
} catch (NoSuchMethodException e) {
System.out.println("Method is not found"); // print something when the method is not found
}
}
public void doSomething() {
System.out.println("I have done something!");
}
}
That would mean starting a whole new JVM just to make a method call.
If you are already "within" class A; what prevents you from calling doSomething() directly? Probably: only your lack of skills. If so, then work on your skills; and don't go for the next best solution you heard somebody mention how things might be done!
In essence: a self-claimed geek should always understand each and any concept he is using in his programs. If you want to use reflection, then study what reflection is about.
And please note: letting your users pass in arbitrary strings to have them executed, is a huge security NO GO. You should have mentioned in your question that you want to do this on purpose; and that you are fully aware of the potential consequences of doing so!
EDIT; given your latest comments.
In this case, a solution could be as simple as:
A) you write a new class, like
public class Invoker {
public static void main(String[] args) {
A.doSomething();
or if doSomething isn't static, you will need
A someA = new A( ... however you can create instances of A
A.doSomething()
B) Compile that, and then you can simply send a command like
java -cp WHATEVER Invoker
into your existing application. Of course, you have to work out the details; like providing a valid classpath to that call to java (that classpath has to include the location where Invoker.class lives; and of course A.class; and all of the dependencies that A has).
But keep in mind: doSomething() is executed in the scope of a different JVM. That means that most likely, it will not at all affect class A in that JVM where you trigger the call to exec!
We all know what the code below does
class Demo{
public static void main(String b[]){
System.out.println("Argument one = "+b[0]);
System.out.println("Argument two = "+b[1]);
}
}
My question (infact curiosity) is, if this application is a daemon that is running and java based server waiting for clients to do socket stuff with it, can I run the application again, and pass new parameters to it ? Basically I am looking at not implementing a cli kinda thing. I need it simple.
Edit : I want to change / add more parameters at runtime. But if I run the app with new parameters, wont it start another instance ?
No, you can't modify the arguments passed after the application started.
The array used to retreive the parameters is populated when it starts and cannot be altered.
If the application is a server, you should be able to implement a CLI rather easily with a simple thread waiting for input.
Seems like you have an existing application that is being run as a command line application right now. It is being invoked as and when required from command line passing the appropriate command line parameters. And now what you would like to do is host this same application as a daemon service which gets invoked as and when the parameters come over a port it is listening to.
Assuming your goal is the above and for whatever reason you want to retain the above main() signature, the key is to realize that the main() method is also like any other static method which can be invoked by a class reference. So the following is possible:
class SocketListener extends Thread {
public void run() {
// Code for listening to socket that calls invokeDemo()
// method below once it detects the appropriate args.
}
private void invokeDemo(String[] args) {
// You can invoke the main method as any other static method.
Demo.main(args);
}
}
This would just treat Demo class as part of a library it is using and not launch any other application. If you do want to launch it as an application (because of some special reason), you would need to use the Process and Runtime classes of java.
I am using the tool monit to start/stop a process. I have a java file as follows:
class test {
public void start()
{
//do something
}
public void stop()
{
//do something
}
}
I want to call the start func when a start command is issued from monit and vice versa. I cannot seem to find a good tutorial explaining what steps I need to take for executing the start and stop method. do I need to write a bash script? and monit will call the bash script which in turn calls the java method?
The entry point into a java program is the main method.
public static void main(String [] args)
{
// args carry the command line arguments.
}
In your case, you should create an instance of test and call start() method on that instance.
public static void main(String [] args)
{
test obj = new test();
obj.start();
}
Java's Runtime class provides an option to add a shutdown hook that gets called when the java program is being terminated. You write a simple thread class that has access to the test instance created in the main method above so that when the shutdown hook thread's run method is called, you delegate it to test instance's stop method.
Hope this helps.
As in the title, I want to test a method like this:
public void startThread()
{
new Thread()
{
public void run()
{
myLongProcess();
}
}.start();
}
EDIT:
Judging by comments I guess it is not very common to test if a thread starts or not. So I've to adjust the question... if my requirement is 100% code coverage do I need to test if that thread starts or not? If so do I really need an external framework?
This can be done elegantly with Mockito. Assuming the class is named ThreadLauncher you can ensure the startThread() method resulted in a call of myLongProcess() with:
public void testStart() throws Exception {
// creates a decorator spying on the method calls of the real instance
ThreadLauncher launcher = Mockito.spy(new ThreadLauncher());
launcher.startThread();
Thread.sleep(500);
// verifies the myLongProcess() method was called
Mockito.verify(launcher).myLongProcess();
}
If you need 100% coverage, you will need to call startThread which will kick off a thread. I recommend doing some sort of verification that the thread was stared (by verifying that something in myLongProcess is happening, then clean up the thread. Then you would probably do the remainder of the testing for myLongProcess by invoking that method directly from your unit test.