I have tried to understand dependency injection and not quite gotten it, except I have managed to pick up the understanding that it makes it hard to understand somebody else's code. :'(
Anyway, I'm not sure how to briefly describe my problem but I will try. I am currently the sole coder working on a Java project that's been worked on by dozens of loners over about six years. It makes heavy use of Google's Guice library. I'm supposed to take some existing code and implement it differently; specifically, use the existing methods for password authentication and, instead of applying it to each JMenuItem in a JMenu, apply it to the whole JMenu, so that if the wrong password or no password is entered, all JMenuItems are disabled. This doesn't happen if the password is wrong, leading me to believe the problem is in the if statement, which is a long string of dependencies in itself:
if (!ViewScanApp.getApplication().getHistoryManager().isAuthenticated())
I trace my way back through this, to find that the HistoryManager class is an interface, and there my path seems to die; there's no code there, and it doesn't make a reference to any other class. I have found the end of the path through random exploration of the 100-odd classes in the project, but I can't quite seem to connect them. I cannot find where the first class I can find on the other end of this stack, AccessManagerImpl, gets called.
I could use an explanation of dependency injection that might be applicable to this situation. Thank you so much!
Assuming there's no #ImplementedBy annotation on the HistoryManager interface, you'll need to examine the Guice Module that is responsible for binding this type.
In Eclipse, there is a command to look for occurrences of a class. I'll bet that Netbeans has something similar. Use it to look for occurrences of HistoryManager. At least one of these should occur in a class that implements com.google.inject.Module (or extends AbstractModule). You'll likely see something like
protected void configure() {
…
bind(HistoryManager.class).to(HistoryManagerImpl.class);
…
}
Or, if you like quick-and-dirty empiricism, you can throw in a println():
HistoryManager mgr = ViewScanApp.getApplication().getHistoryManager();
System.out.println("HistoryManager implementation: " + mgr.getClass());
if (!mgr.isAuthenticated())
…
However you locate it, HistoryManagerImpl class is where you'll want to pick up the trail.
I haven't used it, but the Guice graphing tool might be helpful too.
Fire up a debugger. It will walk you through the exact class that is implementing that interface (assuming you have the source code to it)
Whenever you have an interface definition in Eclipse which is injected with Guice, instead of using F3 to go to the defintion which you would do if it was a class, then use Ctrl-T to choose among the implementations of that interface.
If you have more than one to choose from, then you need the module bindings printed out so you know which one to pick. Unfortunately Eclipse doesn't understand injection yet.
Related
I have some importand methods in code that are used in a wrong way, people don't get the whole context of the process and invokes wrong methods, for example setters. If I had something like #Deprecated it could highlight / strike/ underline methods and show som info when somebody uses it. For example someone set some variables that are even not persisted as he thought that it would persist. Another person changed one method and spoiled dozen of usecases becaouse he didnt know about them..
I use Java7 and IntelliJ Idea 14
Instead of using an annotation, program defensively, check if the parameters you get make sense. Write tests to verify what happens when invalid input is provided.
I think Automated Tests, Good Method Names and such will do more good than some fancy IDE plugin to stop other developers from invoking wrong methods.
Is there any diff tool specifically for Java that doesn't just highlight differences in a file, but is more complex?
By more complex I mean it'd take 2 input files, the same class file of different versions, and tell me things like:
Field names changed
New methods added
Deleted methods
Methods whose signatures have changed
Methods whose implementations have changed (not interested in any more detail than that)
Done some Googling and can't find anything like this...I figure it could be useful in determining whether or not changes to dependencies would require a rebuild of a particular module.
Thanks in advance
Edit:
I suppose I should clarify:
I'm not bothered about a GUI for the tool, it'd be something I'm interested in calling programmatically.
And as for my reasoning:
To workout if I need to rebuild certain modules/components if their dependencies have changed (which could save us around 1 hour per component)... More detailed explanation but I don't really see it as important.
To be used to analyse changes made to certain components that we are trying to lock down and rely on as being more stable, we are attempting to ensure that only very rarely should method signatures change in a particular component.
You said above that Clirr is what you're looking for.
But for others with slightly differet needs, I'd like to recommend JDiff. Both have pros and cons, but for my needs I ended up using JDiff. I don't think it'll satisfy your last bullet point and it's difficult to call programmatically. What it does do is generate a useful report for API differences.
I would like to build my own custom DI framework based on Java annotations and I need a little direction to get started. I know it would be much easier to use one of the many wonderful frameworks out there such as guice or spring, but for the sake of my own curiosity, i'd like to build my own.
I'm not very familiar with annotations, so i'm having a bit of trouble finding resources and would really appreciate someone just sort of spelling out a few of the steps i'll need to take to get started.
As fore mentioned, id like to take a factory approach and somehow label my getters with an #Resource or #Injectable type annotation, and then in my business classes be able to set my variable dependencies with an #Inject annotation and have the resource automatically available.
Does anyone have any sort of resource they can pass along to help me understand the process of tagging methods based on annotations and then retrieving values from a separate class based on an annotation. A little direction is all I need, something to get me started. And of course i'll be happy to post a little code sample here once I get going, for the sake of others future reading of course.
EDIT
The resources I am using to put this together:
Java Reflection: Annotations
How to find annotations in a given package: Stack Overflow ?
Scanning Annotations at Runtime
I have not actually finished writing this yet, but the basic task list is going to be as follows (for anyone who might be interested in doing something similar in the future)
At class runtime scan for all #Inject fields and get object type.
Scan all classes (or just a specific package of classes (I haven't
decided yet)) for annotated methods #InjectableResource.
Loop all annotated methods and find the method that returns the
object type I am looking for.
Run the method and get the dependency.
It will also be helpful to note that when scanning all the classes I will be using a library called Javassist. Basically what this does is allows me to read the bytecode information of each class without actually loading the class. So I can read the annotation strings without creating serious memory problems.
Interesting that you want to build your own. I love Google Guice - it makes code so elegant and simple.
I've used this guide before which I found pretty useful for learning about annotations and how you can pull them out of classes and methods.
You will have to define your own Annotations which is done using #interface. Then you will have to define some kind of class for doing bindings e.g. where you see an interface bind in this concrete class. Finally, you will need some logic to pull it altogether e.g. go through each class, find each annotation, and then find a suitable binding.
Give consideration to things like lazy instantiation through Reflections and singletons. Guice, for example, allows you to use a singleton so your only using one instance of the concrete class, or you can bind a new version each time.
Good luck!
Have a look at the following methods:
java/lang/Class.html#getAnnotation(java.lang.Class)
java/lang/Class.html#getAnnotations()
java/lang/Class.html#getDeclaredAnnotations()
Methods of the same name also exist for the java/lang/reflect/Method, java/lang/reflect/Field and java/lang/reflect/Constructor classes.
So in order to use these sorts of methods, you need to know a bit about Java reflection.
I'm trying to make a code template that will generate tostring, constructor from field, and a default constructor.
I already looked at Useful Eclipse Java Code Templates and in http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.user/reference/ref-tostring-templates.htm but it was not what I was looking for.
I tried this plugin http://eclipse-jutils.sourceforge.net/ but I still need to manually select an option in the menu (and it doesn't have a "constructor from fields" option).
I need to generate these methods and constructors for more then 100 classes so this the best way i found coz eclipse dont give tool to do it for more then one class and for this one class that he give this tool i need to do it one by one the (generate tostring ,constructor from field and also default constructor)
i will love to some help or some advice on a way to create these methods for all my classes, automatically.
thanks in advance.
I don't know of a plugin that will do this for multiple classes.
I'd just do it manually, even though it'd take time.
You could also use reflection and a scripting language like Groovy/JRuby/etc. to create the constructors, and rely on something like Commons' ToStringBuilder to create a toString, or just use reflection again.
(One problem is if you don't want a property in the constructor or toString you need to have a mechanism to tell the generator as much.)
I have just used Practically Macros, within a few minutes of install from the market place, I could generate *constructors*, getters / setters, toString, hashcode and equals (basically chaining the standard eclipse commands) in a single command. Just what I was looking for and saved me loads of time. I can also see a lot more uses for it, well done to Earnst (the creator).
This seems like it should be fairly straight-forward, but I can't see anything obvious. What I basically want to do it to point at a method and refactor->extract class. This would take the method in question to a new class with that method as top level public API. The refactoring would also drag any required methods and variables along with it to the new class, deleting them from the old class if nothing else in the old class is using it.
This is a repetitive task I often encounter when refactoring legacy code. Anyway, I'm currently using Eclipse 3.0.2, but would still be interested in the answer if its available in a more recent version of eclipse. Thanks!
I don't think this kind of refactoring exists yet.
Bug 225716 has been log for that kind of feature (since early 2008).
Bug 312347 would also be a good implementation of such a refactoring.
"Create a new class and move the relevant fields and methods from the old class into the new class."
I mention a workaround in this SO answer.
In Eclipse 3.7.1 there is an option to move methods and fields out of a class. To do so:
Make sure the destination class exists (empty class is fine, just as long as it exists in the project).
In the source class, select the methods that you want to remove (the outline view works great for this), right click on the selection, and choose Move
Select the destination class in the drop down/Browse
Your members are now extracted. Fix any visibility issues (Source > Generate Getters and Setters is very useful for this) and you are all set.
This seems like it should be fairly
straight-forward...
Actually, Extract Class is one of the more difficult refactorings. Even in your simple example of moving a single method and its dependencies, there are possible complications:
If the moved method might be used in code you don't know about, you need to have a proxy method in the original class that will delegate to (call) the moved method. (If your application is self-contained or if you know all the clients of the moved method, then the refactoring code could update the calling code.)
If the moved method is part of an interface or if the moved method is inherited, then you will also need to have a "proxy method".
Your method may call a private method/field that some other method calls. You need to choose a class for the called member (maybe in the class that uses it the most). You will need to change access from "private" to something more general.
Depending on how much the original class and the extracted class need to know about each other, one or both may need to have fields initialized that point to the other.
Etc.
This is why I encourage everybody to vote for bug 312347 to get fixed.
Have you tried the Move feature of the Refactor group ? You can create a helper class and move there anything you want.