Suppose I have java code like this (only as Example):
public void someMethod(){
int a = 3;
int b = 2; // <-- stay debug here
a = b + 2;
System.out.prinln(a);
}
It is possible to skip execution of line a = b + 2; and go immidiatly to System.out.prinln(a);?
P.S. I use Intellij Idea 12.
It's not possible with the debugger to not execute parts of the code.
It is however possible to execute extra code and change values on variables so if you need to exclude one row from execution during debug you will have to alter your code to prepare for that kind of debugging.
public void someMethod() {
int a = 3;
int b = 2;
boolean shouldRun = true;
if (shouldRun) {
a = b + 2;
}
System.out.prinln(a);
}
You would then set a break point that changes the value of shouldRun without stopping execution. It can be done like this.
Note that
Suspend isn't checked
Log evaluated expression is used to alter a variable when the break point is hit
IntelliJ recently published a blog post about a plugin called Jump to Line that can accomplish this, even though IntelliJ itself doesn't have this functionality. It really is surprising that IntelliJ still doesn't have this functionality, when Visual Studio has had it for so many years!
https://blog.jetbrains.com/idea/2020/08/jump-to-any-line-while-debugging/
It is possible to skip lines only if you use hotswapping, or put in other words, code reloading tool - add code changes/new code at runtime. Hotswapping is the functions of replacing components without shutting down the system. Hotswapping can also refer to the ability to alter the running code of a program without needing to interrupt its execution.
There are various hotswapping tools like: JRebel (https://zeroturnaround.com/software/jrebel/) or HotSwapAgent (http://www.hotswapagent.org/)
You avoid having to rebuild the entire application to reload code changes, this is a huge time savings. Instead of running your full build process, simply use the compiler built into your IDE and the hotSwap agent/tool will reload the code into the JVM.
In this case, it would not be actually skipping, but you can just comment/change the lines and reload it. This tools are quite awesome!!!! It greatly speeds up the development/debugging process.
You can't just skip 'line execution' when debugging. You can press F8 to step over.
An option is to skip the execution of the rest of the method. You can invoke Force Return and even set a return value.
As stated here by ntotomanov , you can use HotSwap for it.
but just adding that i use remote debug to debug my Docker based apps , so if i want this kind of functionality i just comment out the code , and go to Build -> Recompile class or Rebuild Project . then Intellij issues Build & Attempting to HotSwap the code ! in case you did small thing like comment out the code it most of the times always succeeds. happy debugging.
It is not possible to skip the EXECUTION of the lines in IntelliJ and even in Eclipse.
Only thing you can do is you can do step over (F8)-which will trace line by line without
going inside any function.
One more thing is Step out(Shift+F8)- which will go to next debug point directly by executing in between lines in that single step.
Related
Whenever I program, I seem to accumulate a lot of "trash" code, code that is not in use anymore. Just to keep my code neat, and to avoid making any expensive and unnecessary computations, Is there an easy way to tell if there is code that is not being used?
One of the basic principles which will help you in this regard is to reduce visibility of everything as much as possible. If a class can be private don't make it default, protected or public. Same applies for methods and variables. It is much easier when you can say for sure if something is not being used outside a class. In cases like this even IDEs like Eclipse and IntelliJ Idea will suggest you about unused code.
Using this practice while developing and refactoring code is the best way to clean unused code confidently without the possibility of breaking the application. This will help in scenarios even when reflection is being used.
It's difficult to do in Java since it's a reflective language. (You can't simply hunt for calls to a certain class or function, for example, since reflection can be used to call a function using strings that can only be resolved at runtime.)
So in full generality, you cannot be certain.
If you have adequate unit tests for your code base then the possibility of redundant code should not be a cause for concern.
I think "unused code" means the code that is always not executed at runtime. I hope I interpreted you correctly.
The way to do a simple check on this is very easy. Just use IntelliJ IDEA to write your code. It will tell you that parts of your code that will never be executed and also the parts where the code can be simplified. For example,
if (x == 5) {
}
And then it will tell you that this if statement is redundant. Or if you have this:
return;
someMethod();
The IDE will tell you that someMethod() can never be reached. And it also provides a lot of other cool features.
But sometimes this isn't enough. What if you have
if (x == 5) {
someMethod();
}
But actually in your code, x can only be in the range of 1 to 4? The IDE won't tell you about this. You can use a tool that shows your code coverage by running lots of tests. Then you can see which part of your code is not executed.
If you don't want to use such a tool, you can put breakpoints in your methods. Then run some tests by hand. When the debugger steps through your code, you can see exactly where the code goes and exactly which piece(s) of code is not executed.
Another method to do this is to use the Find/Replace function of the IDE. Check if some of your public/private methods are not being called anywhere. For example, to check whether someMethod() is called, search for someMethod in the whole project and see if there are occurrences other than the declaration.
But the most effective way would be,
Stop writing this kind of code in the first place!
i think the best way to check that is to install a plugin of coverage like eclemma and create unit and integration tests to get 100% of coverage of the code that accomplish the use code/task you have.
The code that don't need to be tested or don't pass over it after the tests are completed and run, is code that you are not using
Try to avoid accumulating trash in the first place. Remove stuff you don't need anymore. (You could make a backup or better use a source code management system.)
You should also write unit tests for your functions. So you know if it still works after you remove something.
Aside from that, most IDEs will show you unused local variables and private methods.
I do imagine situation when you have app developed by years and some part of your functions doesn't used anymore even they still working. Example: Let's assume you make some changes on internal systems when specific event occured but it is not occurs anymore.
I would say you could use AspectJ to obtain such data / log and then analyze after some time.
I have searched and found that indeed Eclipse does not support this 'direct' feature. But, Did I stil miss something? and Is it present in other IDEs?
Let me elaborate my question more -
if a statement falls under execution flow based on an expression evaluation, then why can't we force execute it? (without the execution of the expression).
For example consider this -
... if(bool returnsABoolean) {
<execute some statement>;
}
...
Can the execution of 'if' be skipped and the statement be executed as a 'next statement'? (I obviously can control the value of 'returnAsBoolean' in the Variables view; but can I not skip (in a controlloed manner) all the statements until a particular statement in the execution?)
Highlight the code you want to run and right-click/Execute or press Ctrl+U.
Alternatively to "Execute", use "Display" (Ctrl+Shift+D) or "Inspect" (Ctrl+Shift+I) to see the result.
Looks like you want the 'Display' view - in the Debug perspective, do :
Window -> ShowView -> Display.
You can enter Java statements to execute there (you have to select the bit of text each time that you want to execute)
http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fdisplay%2Fref-display_view.htm
Debugging allows you to run a program interactively while watching the source code and the variables during the execution.
So debugging is nothing but executing program but inspecting the elements during execution but you can not jump into something which is not there in execution.
You can use keyboard buttons F5,F6 ,F8 etc. (For Eclipse) and other Shortcuts during debugging for your convinience but you can't jump to something directly which is not in the execution sequence.
Debugging Shortcuts:
F5 Step into
F6 Step over
F8 Resume and will take you to the break point
Ctrl+Shift+B Toggle breakpoint
Ctrl+Shift+D Display Info of current statement
Ctrl+Shift+I Inspect the selected element
You can Skip some code by the use of breakpoint you can directly jump to specific point and avoid debugging of code which you believe works fine.Or you can jump out code snippet if you want to.
The question really was to set the Instruction pointer at will. This has been discussed and through url's i pasted on the comments above - this is not an eclipse feature (yet).
Consider a java program with many variables and some of them are counters for loops I want to see the values of these variables as they change with time , WITHOUT putting print statements everywhere in my code.
Why ? I think it can help me to debug easily.
Example-
int a = 7;
for(i=0; i<3; i++)
{
a++;
}
As this program runs I want to get live reports like this:
t is 0, a is 7, i is 0
t is 3, a is 8, i is 1
t is 12, a is 9, i is 2
(t is time, time factor is NOT necessary though)
You can use a debugger. Debuggers will help you keep track of that without actually sending your vars to STDOUT. I recommend DDD because it's free and professionally used. http://www.gnu.org/software/ddd/
Note: to avoid confusion about how it works, DDD works on top of JDB, the Java debugger included in the JDK.
You should use a debugger and put a breakpoint where you want to see the values (in this case at the line with a++). The you can see the value at each iteration.
Most IDEs have debuggers (Intellij IDEA, Eclipse or NetBeans).
This is what debuggers are used for.. to step through your code and check the values of variables. If you want your code to print out statements every so often, you can use the Timer class and TimerTask to print out the value of a variable for a specified time interval.
1. Use Debugger, If you are using an IDE like Eclipse, IntelliJ, then its build in, into it.
2. If you are not using any debugger, then you can use jdb The Java Debugger.
See JPDA for the debugger architecture specifications.
Eclipse doesn't support this if I'm not mistaken but in Intellij IDEA you can setup breakpoint in a way that doesn't stop your application running when hit it but instead evaluates and logs particular expression you specified. The same functionality available for those who use ms visual studio:)
I'm a newbie to Android and Java--lots of experience with C/C++/C#.
I have in interface that looks like this:
class WellNamedClass {
void greatMethodToCallWhenever() { /*...*/ }
void debugOnlyMethod() { /*...*/ }
}
In the the languages mentioned above, I would either #ifdef the entire debugOnlyMethod method out or #ifdef the implementation out so it simply does nothing, but Java doesn't have a preprocessor.
I'm totally comfortable with having the code there and checking at run-time whether we are in a debug build, but I can't even find a way of doing that.
I've found suggestions like this one where you create a class with a constant indicating whether debug (or whatever else you want) is enabled. This could work, but then you have to manually change code to get a debug vs. a release build.
Has anyone else solved this problem? Thanks.
I don't know why do you need this, BTW you can put a static global variable, like this:
class WellNamedClass{
public static final boolean DEBUG = true;
...
}
And check your debug method with an if statement, like:
if(WellNamedClass.DEBUG){
debugOnlyMethod();
}
Starting with java you could play with this.
When you get more experience, you could try annotations, aop, or any other advanced programming technique.
This could work, but then you have to manually change code to get a
debug vs. a release build.
One popular approach is to pass system property using -D flag to the VM. You can then either use System.getProperty directly or initialize a static field from that property.
System.getenv will also work.
I think the method we're going to use is have a JNI call into our native component that will tell us whether we are running in debug mode. We have to have the native component anyway, and will make a few JNI calls at startup so it's a relatively simple solution, since C++ has a preprocessor.
Long overdue but it might help anyone else who ends up here in the future.
Simple answer; do not use conditional logic to determine what state the build is in. Configure a build variant and use the appropriate source sets for your configured build. It seems like more work up front but ultimately will save you a ton of time and trouble in the long run.
I have a webapp running that has a bug. I know how to fix it in the sources. However I cannot redeploy the app as I would have to take it offline to do so. (At least not right now).
I now want to fix the code "at runtime". Surgery on the living object, so to speak.
The app is implemented in Java and is build on top of Seam. I have added a Groovy Console to the app previous to the last release. (A way to run arbitrary code at runtime)
The normal way of adding behaviour to a class with Groovy would be similar to this:
String.metaClass.foo= { x -> x * x }
println "anything".foo(3)
This code added the method foo to java.lang.String and prints 9. I can do the same thing with classes running inside my webapp container. New instances will thereafter show the same behaviour:
com.my.package.SomeService.metaClass.foo= { x -> x * x }
def someService = new com.my.package.SomeService()
println someService.foo(3)
Works as excpected. All good so far.
My problem is now that the container, the web framework, Seam in this case, has already instantiated and cached the classes that I would like to manipulate (that is change their behaviour to reflect my bug fix).
Ideally this code would work:
com.my.package.SomeService.metaClass.foo= { x -> x * x }
def x = org.jboss.seam.Component.getInstance(com.my.package.SomeService)
println x.foo(3)
However the instantiation of SomeService has already happened and there is no effect.
Thus I need a way to make my changes "sticky". Has the groovy magic gone after my script has been run? Well, after logging out and in again, I can run this piece of code and get the expected result:
def someService = new com.my.package.SomeService()
println someService.foo(3)
So the foo method is still around and it looks like my change has been permanent...
So I guess the question that remains is how to force Seam to re-instantiate all its components and/or how to permanently make the change on all living instances...?
The hotfix is not persistent because the calling code is pure Java, not Groovy.
The Groovy magic in fact stays. But only when called from the groovy environment, that is through other groovy code.
Turns out that in a Java environment, the "Keyhole Surgery Pattern", as coined by Dierk König is only usable to change data at runtime, not code. The full power of the pattern is only accessible in a pure Groovy environment.
Not Groovy, but an alternative approach that works - as long as you don't change / add / remove and method signatures - is to set the Server in debug mode and use Java Hot Code Replacement functionality. Most IDE's support this. The changes are permanent and applied to instantiated components as well.
Requires of course that the app server is already configured with the a debug console or allows to enable it after the start.