I have a List of classes which I can iterate through. Using Java is there a way of finding out where these classes are used so that I can write it out to a report?
I know that I can find out using 'References' in Eclipse but there are too many to be able to do this manually. So I need to be able to do this programmatically. Can anyone give me any pointers please?
Edit:
This is static analysis and part of creating a bigger traceability report for non-technical people. I have comprehensive Javadocs but they are not 'friendly' and also work in the opposite direction to how I need the report. Javadocs start from package and work downwards, whereas I need to start a variable level and work upwards. If that makes any sense.
You could try to add a stacktrace dump somewhere in the class that isolates the specific case you are looking for.
public void someMethodInMyClass()
{
if (conditions_are_met_to_identify)
{
Thread.dumpStack();
}
// ... original code here
}
You may have to scan all the sources, and check the import statements. (Taking care of the * imports.. having to setup your scanner for both the fully Qualified class name and its packagename.*)
EDIT: It would be great to use the eclipse search engine for this. Perhaps here is the answer
Still another approach (probably not complete):
Search Google for 'java recursively list directories and files' and get source code that will recursively list all the *.java file path/names in a project.
For each file in the list:
1: See if the file path/name is in the list of fully qualified file names you are interested in. If so, record is path/name as a match.
2: Regardless if its a match or not, open the file and copy its content to a List collection. Iterate through the content list and see if the class name is present. If found, determine its path by seeing if its in the same package as the current file you are examining. If so, you have a match. If not, you need to extract the paths from the *.import statements, add it to the class name, and see if it exists in your recursive list of file path/names. If still not found, add it to a 'not found' list (including what line number it was found on) so you can manually see why it was not identified.
3: Add all matches to a 'found match' list. Examine the list to ensure it looks correct.
Not sure what you are trying to do, but in case you want to analyse code during runtime, I would use an out-of-the box profiler that shows you what is loaded and what allocated.
#Open source profilers: Open Source Java Profilers
On the other hand, if you want to do this yourself (During runtime) you can write your own custom profiler:
How to write a profiler?
You might also find this one useful (Although not exactly what you want):
How can I list all classes loaded in a specific class loader
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html
If what you are looking is just to examine your code base, there are really good tools out there as well.
#see http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
Related
I have a tool that will list failed tests, and I would like a way to open a fully qualified class and goto a method in Eclipse with a single string I can copy from the results. It can use any pattern whatsoever (I can change the test results layout), but could be something like this example:
com.my.package.StringUtilTest:testValueOf
I shall use it for re-running tests, but could work with any methods. It could go to the first option when there are overloads (won't matter for me). It could also list all options and allow me to paste the string and enter to go to the first option (being the only one in my case), or selecting the correct one from the very narrowed down options, just like Ctrl + O will do (note Ctrl + O will work on current file only though). It could even accept (or require!) the parameter types, won't matter. Anything like that would be a huge thanks. Some place where I can paste a single string on (in any way that it may have to be) to open a specific method.
I've been looking for a while, could be built-in or configured shortcut, macro, plugin, et cetera, but could neither find nor wrap my head around doing something (not expert on eclipsetalities)... I tried searching for a lot different stuff, but as you can see my problem can be solved with a vast pletora of things (none of which I can find anywhere though).
Eclipse jdt doesn't have it yet, but I believe an open method dialog similar to the open type dialog is in the works.. Please create a bug at bugs.eclipse.org if one doesn't exist describing what you would want in such a dialog.
Following on from my previous question, my program doesn't detect the 300 images that have just been created in a particular directory; instead, it only detects desktop.ini, which is not the case as I can physically see that the files have been created within said directory and do exist.
Can somebody please explain why this happens as when I run the program the next time, it seems to work just fine?
The only way that something is detected within the directory on the first run is when there is at least one file which exists in the directory before the program is compiled and executed.
Many thanks.
UPDATE: Files are detected as follows:
//Default greyscale image directory (to convert from greyscale to binary).
static File dirGrey = new File("test_images\\Greyscale");
//Array of greyscale image filenames.
static File imgListGrey[] = dirGrey.listFiles();
without knowing how you create the images, this question is akin to 'How many kittens are under my desk right now?'
Are you creating the files yourself? If so, are you closing any file handles referring to those files once they are created?
You're creating the file list in a static array, and it's created when the class containing the array is loaded by the Java class loader, which is probably before you create the image files. That's why the array contains an outdated list.
static is rarely needed, mostly useful for constants (things that never change, such as 42), for pure functions (Math.sqrt()) and a few other special cases. When you use it, you have to learn all the tricky initialization order stuff. Otherwise, just stick with non-static variables.
For those unfamiliar with JNotify, this is a library which provides an easy way to monitor events in a directory.
For instance, when a file gets deleted in the selected folder, the method "fileDeleted" gets called, along with a few parameters. Here's an example of the fileDeleted method:
public void fileDeleted(int wd, String rootPath, String name) {
print("deleted " + rootPath + " : " + name);
}
Now, I would like to know if the deleted file was a file or directory. My usual approach is to create a new File object with the given path, and use the methods isFile() and isDirectory()
However, since this file is already deleted, these methods always return false.
So here's my concrete question: I have the path to a deleted file or directory, how can I tell wether it was a file or a directory? Is there a workaround to this? What's the best practice to do here?
Thank you in advance.
I suggest using a better API for this, like Commons IO. It has this distinction in its interface org.apache.commons.io.monitor.FileAlterationListener and its methods onFile...(), onDirectory...(). Alternatively, and this is probably the best approach, use the new standard feature for this that comes with Java 7, WatchService, as discussed here.
How big is the directory structure you're looking at?
My first instinct is to build an internal representation of the directory structure, using some simple graph traversal algorithm, and then do a lookup every time something is removed to figure out what it was.
<edit>
If you know your directory structure is a strict tree you can use a simple recursion to traverse the file system, and create a map of Files or Strings to boolean, so you can do an easy lookup. Then, once you've got the map built it should be easy to maintain using the JNotify events.
<edit/>
even for medium-sized directories I would think this could be made pretty quick. What is this for? Might there be another way of going about achieving the same goal?
I am facing the same problem. Yet as far as I understand it, Java's WatchService does not allow monitoring of subdirectories, so I cannot use it (task is to monitor changes to a structure containing ~40K folders). I will try and go ahead using the simple (and fallible) heuristic
If it contains a dot ('.'), it's a file.
I will post updates if I come across something more sophisticated...
I'm remote debugging a Java application and (not for the first time) I find myself looking for a value without knowing what variable might hold it (if any at all). This is especially hard to find since I'm stepping through library code rather than my own code, so I was wondering; since eclipse can display the variables currently available on the stack, along with all contained values, is there any way I can search these? Or at the very least dump it out as text somewhere and grep it or something.
I usually do an export to JSON using Jackson's ObjectMapper whenever I find myself into the situation of having to search among a bunch of values caught while debugging. On breakpoint hit, let's say I want to search some string inside a text representation of myObj, which could be some messy POJO deep with nested objects. Just evaluate the following:
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.writeValue(new java.io.File("/tmp/myObj.json"), myObj);
and then go grep your value inside the file you just created.
YMMV: if you have no idea where to start the search you'll have to iterate through what's available on the stack. Also the JSON representation might not be suitable for every kind of search.
I'm not sure about the feature you are asking for but there is another approach you could take. Assuming you know the general area AND the object you are looking for isn't too common, eclipse supports conditional breakpoints so you could set breakpoints on the end of methods chechking the method variables and object state.
You could try evars. I haven't tried the search function, but it allows expanding and exporting all the variables on the stack to a file, which you can then grep for your value. I installed the latest version into Eclipse manually, i.e. putting the jar in the dropins/plugins directory. Worked for me on Eclipse 3.6.1.
I'm working in a java project where a big part of the code was written with a formatting style that I don't like (and is also non standard), namely all method parameters are in uppercase (and also all local variables).
On IntellJ I am able to use "Analyze -> Inspect Code" and actually find all occurrences of uppercase method parameters (over 1000).
To fix one occurrence I can do "refactor > rename parameter" and it works fine (let's assume there is no overlapping).
Is there a way to automagically doing this refactor (e.g: rename method parameter starting with uppercase to same name starting with lowercase)?
Use a Source Parser
I think what you need to do is use a source code parser like javaparser to do this.
For every java source file, parse it to a CompilationUnit, create a Visitor, probably using ModifierVisitorAdapter as base class, and override (at least) visit(MethodDeclaration, arg). Then write the changed CompilationUnit to a new File and do a diff afterwards.
I would advise against changing the original source file, but creating a shadow file tree may me a good idea (e.g. old file: src/main/java/com/mycompany/MyClass.java, new file src/main/refactored/com/mycompany/MyClass.java, that way you can diff the entire directories).
I'd advise that you think about a few things before you do anything:
If this is a team effort, inform your team.
If this is for an employer, inform your boss.
If this is checked into a version control system, realize that you'll have diffs coming out the wazoo.
If it's not checked into a version control system, check it in.
Take a backup before you make any changes.
See if you have some tests to check before & after behavior hasn't changed.
This is a dangerous refactoring. Be careful.
I am not aware of any direct support for such refactoring out of the box in IDEs. As most IDEs would support name refactoring (which is regularly used). You may need to write some IDE plugin that could browse through source code (AST) and invoke rename refactoring behind the scene for such parameter names matching such format.
I have done a lot of such refactorings on a rather large scale of files, using TextPad or WildPad, and a bunch of reg-ex replace-all. Always worked for me!
I'm confident that if the code is first formatted using an IDE like Eclipse (if it is not properly formatted), and then a reg-ex involving the methods' signature (scope, return-type, name, bracket, arg list, bracket) can be devised, your job will be done in seconds with these tools. You might need more than one replace-all sets of reg-ex.
The only time-taking activity would be to come up with such a set of reg-ex.
Hope this helps!