Eclipse Mars (4.5) hot swap code in debugger not working - java

So I updated to Eclipse Mars (4.5) and for some reason I'm unable to use the hot swap code in the debugger. Normally I could do something like this:
public static void main(String[] args){
while(true){
System.out.println("123");
}
}
Then if I started it in debug mode, changed the text to "321", then save, then it would update without the need for restarting it. It behaves exactly like it was run in "Run" mode instead of "Debug".
What I have tried:
Creating a new workspace, creating a fresh project, using the code above, nothing happens
Have several JDKs installed, have tried with java 6, 7 & 8, changed the workspace and/or the project settings to use the different JDKs, nothing happens (the fact that I have several versions of java installed shouldn't matter as it was just the moment I updated eclipse it stopped working)
Tried uninstalling removing any config files to eclipse (on a mac, so that would be every file/folder with the word "eclipse" in the ~/Library folder, ran a "find" search to detect all the files). Then tried to create a new workspace, now project, the code snipped, ran in debug mode, nothing happens on save.
Have also made sure I have "Auto Build" enabled, even tried to "clean" it, and disable auto build, then save the code, then do a manual build while the debugger was running: nothing happens
I'm starting to get desperate as I have a hard time getting work done without having debug mode available so any help/hints in the right direction would be of much appreciation.

HotSwap doesn't work with static methods. However it works fine with instance methods, so it will work on this code:
public class Main {
public static void main(String[] args) {
new Main().f();
}
public void f() {
while(true){
System.out.println("123");
}
}
}

Ok so I finally found the problem. It seems that you can't edit loops while they are running. Say you have a loop like this:
public static void main(String[] args){
while(true){
System.out.println("123");
}
}
Then you can't edit the "123" string.
You can how ever edit methods which are called inside the loop like this:
public static void main(String[] args){
while(true){
System.out.println(methodA());
}
}
public static String methodA(){
return "123";
}
Now you can edit the string "123" and it will update.
This also applies for infinite "for" loops, so guess the rule of thumb is that the method body has to be "re-called" before updating, and it isn't enough to wait for the next loop call.

Related

im trying to create a thread that sends and receives a message in java however im unsure on how to solve the error messages that are displayed [duplicate]

I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:
package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".
It could be that your main method does have the proper signature. In my case I forgot the args.
example:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
Args: You can name the argument anything you want, but most programmers choose "args" or "argv".
Read more here:
http://docs.oracle.com/javase/tutorial/getStarted/application/
When creating a new project - Maven - Java application in Netbeans
the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Create new project - Maven - Java application
(project created: mytest; package created: com.me.test)
Right-click package: com.me.test
New > Java Class > Named it 'Whatever' you want
Right-click package: com.me.test
New > Java Main Class > named it: 'Main' (must be 'Main')
Right click on Project mytest
Click on Properties
Click on Run > next to 'Main Class' text box: > Browse
You should see: com.me.test.Main
Select it and click "Select Main Class"
Hope this works for others as well.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)
I had the same problem in Eclipse, so maybe what I did to resolve it can help you.
In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
In project properties, under the run tab, specify your main class.
Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
// stuff
}
}
This just helps with readability.
If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.
Edit: See peeskillet's answer if adding closing braces doesn't work.
There could be a couple of things going wrong in this situation (assuming that you had code after your example and didn't just leave your code unbracketed).
First off, if you are running your entire project and not just the current file, make sure your project is the main project and the main class of the project is set to the correct file.
Otherwise, I have seen classmates with their code being fine but they still had this same problem. Sometimes, in Netbeans, a simple fix is to:
Copy your current code (or back it up in a different location)
Delete your current file
Create a new main class in your project (you can name it the old one)
Paste your code back in
If this doesn't work then try to clear the Netbeans cache, and if all else fails, then just do a clean un-installation and re-installation of Netbeans.
In the toolbar search for press the arrow and select Customize...
It will open project properties.In the categories select RUN.
Look for Main Class.
Clear all the Main Class character and type your class name.
Click on OK.
And run again.
The problem is solved.
If that is all your code, you forgot to close the main method.
Everything else looks good to me.
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
}}
Try that.
You need to add }} to the end of your code.
You need to rename your main class to Main, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main.
That's all.
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.
My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.
What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..."
Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):
After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):
So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.
I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:
Unexpected Exception
java.lang.ExceptionInInitializerError
Clicking on that link showed me more details of the error:
java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
at java.security.Security.getImpl(Security.java:695)
at java.security.MessageDigest.getInstance(MessageDigest.java:167)
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)
That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))
Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.
Had the same problem after opening a project that I had downloaded in NetBeans.
What worked for me is to right-click on the project in the Projects pane, then selecting Clean and Build from the drop-down menu.
After doing that I ran the project and it worked.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)

Create a stoppable java program (daemon)

Starting a java command line application is easy, you only have to write the following line in a command prompt (in the directory where the app is located).
java myApp.java
However, to stop the application in the right way, so that you ensure that all unmanaged resources are cleaned (and anything that must be done before stop, will be done) requires custom code.
The app will run in a debian system with no GUI as a daemon (it will run in background).
Here below I write the skeleton of the code.
public class MainClass {
public static void main(String[] args) throws Exception {
boolean stop = false;
while(!stop){
doSomething();
}
stop();
}
private static void doSomething(){
//Main code of app here
}
private static void stop(){
beforeStop();
System.exit(0);
}
private static void beforeStop(){
clean();
//Code to do anything you have to do before stop
}
private static void clean(){
//Code to clean unmanaged resources
}
}
As you can see, the app will run 24/24 and won't stop until you don't stop it.
Killing the process (as some people suggest) is not a good solution, because (for example) some unmanaged resources might not be cleaned properly.
I need a code which makes possible to alter the boolean variable "stop" from OUTSIDE.
The best solution is the one which makes possible to stop the app with a command similar to the start command, see pseudo code below (executed in a command prompt, in the directory where myApp.java is located).
myApp.java stop=true
But if it's not possible, the second option would be to have an other java command line app, which stops myApp.java, so that I could stop myApp.java with the following code
java stopMyApp.java
Is someone able to suggest a useful code example?
You can use a text file with one word. Your program reads it every x seconds and depending on that word it will autostop.
You can change the file text content by hand or with another program you can run whenever you want.
Even better you can use WatchService API (Java 7) or VFS API from Apache Commons to be notified when the file changes.
If you use a DB you can use it instead of a plain file.

Bytecode Hotswap - perplex

I have no idea anymore. Since today 14pm the hot-code replace does not work anymore.
I had jdk8_74x64 installed on win10x64.
I test it using this code in a simple project (without maven and without dependencies):
public class Test{
public static void main(String[] args){
System.out.println("hi"); // breakpoint here, it stops always
System.out.println("ho"); // on suspending i change this to "hoy".
}
}
Start eclipse with new workspace - still not working
Restart computer - still not working
Uninstall all JDK/JRE and remove all javaws.exe, install again - still not working.
Uninstall eclipse, reinstall eclipse - still not working
Installed netbeans, using "apply code changes" - still not working.
Delete jdk with all javaws.exe, delete eclipse, uninstall netbeans, use new user, install jdk 8u31x64 install netbeans - still not working
Installed idea-community-edition15+jetbrains, change ho to hoy and apply class-changes (idea notifies me 1 class reloaded) - still not working.
How to get hot-code-replace working?
Hm,
public class Test{
public static void main(String[] args){
System.out.println("hi"); // breakpoint here, it stops always
System.out.println("ho"); // on suspending i change this to "hoy".
}
}
does not work but
public class Test{
public static void main(String[] args){
foobar();
}
public static void foobar(){
System.out.println("hi"); // breakpoint here, it stops always
System.out.println("ho"); // on suspending i change this to "hoy".
}
}
Works great everywhere.

Drop to frame feature disabled in Eclipse Debug while running testcases using JUnit

Environment:
Linux, Eclipse Juno, Java 7, JUnit
When a simple application (a java class with main method) is run in debug mode, 'Drop to Frame' feature works fine in Eclipse. However if the same method is invoked from a junit test case, 'Drop to Frame' feature is disabled in Eclipse. From the documentation
Note this command is only available if the current VM supports drop to
frame and the selected stackframe is not the top frame or a frame in a
native method.
As we can see from the stack frames in Debug window when a junit test case is run, there is a frame 'NativeMethodAccessorImpl.invoke' which is native. I'm assuming this is the reason for 'Drop to Frame' being disabled.
Let me know if this reasoning is correct and if yes, any workarounds available to overcome this.
I use Eclipse Luna, Java 7 under Windows.
The situation is still as described: "Drop to frame" is disabled for the test method which immediately follows the 'NativeMethodAccessorImpl.invoke' frame.
The disabled state of the "Drop to frame" is bound to method canDropToFrame() respective supportsDropToFrame() in class org.eclipse.jdt.internal.debug.core.model.JDIStackFrame,
(in my distribution) part of plugins/org.eclipse.jdt.debug_3.8.102.v20150115-1323/jdimodel.jar.
Method supportsDropToFrame() checks if a specific frame can be dropped, and tests
the JVM must support to drop frames
the frame must not be the top most frame
the frame must not be native
the prior frame must not native
So the assumption of Ramesh was right.
This is the original code snippet for tests 3 + 4:
int index = 0;
JDIStackFrame frame = null;
while (index < frames.size()) {
frame = (JDIStackFrame) frames.get(index);
index++;
if (frame.isNative()) {
return false;
}
if (frame.equals(this)) {
if (jdkSupport) {
// JDK 1.4 VMs are currently unable to pop the
// frame directly above a native frame
if (index < frames.size()
&& ((JDIStackFrame) frames.get(index))
.isNative()) {
return false;
}
}
return true;
}
}
The comment suggests that it was written in JDK 1.4 times, so maybe in the meantime the JVM can now also drop frames above native frames.
I created a patched version of JDIStackFrame, which skips test 4.
Now when pausing in a Junit test method, "Drop to frame" was enabled, as expected.
But when actually dropping the frame, I received an error message box which stated
"com.sun.jdi.InternalException: Got error code in reply: 32 occurred popping stack frame".
I assume that this is a JDWP error code.
Therefore it seems that such a "Drop to frame" does not work in JDK 1.7 (don't know about 1.8), and it's not a Eclipse thing.
This is an old one, but for the time being this is still an issue with Eclipse 2018-09, Java 1.8 and testng as test runner. The workaround (simple and obvious) is to extract the contents of the test into another method, debug it and then inline it back. E.g.:
#Test
public void test() {
// test goes here
assertTrue(true);
}
One may use refactoring shortcuts to speed up things: select the body of the test, press Alt+Shift+M, enter name 'inner', and the result is:
#Test
public void test() {
inner();
}
private void inner() {
// test goes here and 'drop-to-frame' works well
assertTrue(true);
}
When done debugging, inline it back by pressing Alt+Shift+I while inside inner().
I've always dealt with this problem by splitting between the #Test function and a thunk that I can drop frames into.
Pre JDK-8, I'd do this:
#Test
public void testSomeFooInBar() {
drop_to_frame_testSomeFooInBar();
}
private void drop_to_frame_testSomeFooInBar() {
assertTrue(somethingOrWhatever);
}
Even though it's verbose, I insist/insisted in calling my thunks after the test functions, with the name indicating what they are for (to "jump/drop to frame"). This is always necessary because there's always someone who does "refactoring" without reading comments and start removing the thunks as "unnecessary."
With JDK 8 and above, I do this:
#Test
public void testSomeFooInBar() {
final Runnable drop_to_frame = () -> {
assertTrue(somethingOrWhatever);
};
jump_to_frame.run();
}
Simpler. Eclipse will allow you to set a breakpoint inside the runnable lambda and drop to frame as many times as you needed (assuming your logic is sufficiently re-entrant.)

Error: Could not find or load main class hello.world.HelloWorld

I am trying to run this project called "hello user". I am new to Java, so wrote a simple program that takes your name, and displays "Hello ". while Running it, I get the following error:
run:
Error: Could not find or load main class hello.world.HelloWorld
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
But when I run file HelloWorld.java, it does it fine
I am doing this on Netbeans IDE 7.2
Rather than the coding error, it could be related to IDE. Since the "Run File" runs okay, but 'Run Project" does not, I believe you have something to set up in IDE itself. Right click the project, and select "Set is as Main", now run the project. I am just giving it a guess, may not help you. But it worth a shot.If it does not help, please paste your code too.
Your class needs a public static void main(String[] args) function. And moreover I suspect that the error could be in the package.
If you want your class in <main_package>.<sub_package>, The directory structure is
- main_package
- sub_package
-HelloWorld.java
And be sure to write your class like this.
package main_package.sub_package;
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello " + args[o]);
}
}
This is all due to the naming convention in Java
You need to run the .class file containing the public static void main(String[] args) method..
Here, your HelloWorld.java file might contain a class with main() method.. So, you can run it..
This is because, execution of any Java program starts with the invocation of main().. JVM needs an entry point to your code.. Which is main().. If it doesn't find one.. It will not run..
So, make sure, whatever class file you are running, it should have main() method..
UPDATE :- And for the starting point, may be you can skip using packages.. Just go with plain Java class without packages..
This message can also appear in Eclipse (Juno 4.2.2 in my case) and I have found two potential causes for it.
In my cases:
1. a DTD was in error. I deleted the file and that solved the issue*.
2. having cleaned the project, an external Jar that I had built externally had been deleted as could be seen from Properties -> Java Build Path -> Libraries.*
*Having solved either of the above issues, it was necessary to restart Eclipse
if you are using intellij idea then just rebuilding (clean and build) project might solve your problem . because intellij might be still trying to load the old classes which are not there or changed
Make sure you call looks like below:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello user");
}
}
To run a Java class in stand alone mode, public static void main(String[] args) is the entry method, which is must.

Categories

Resources