guys! Could you tell me please, how we can to initialize field, using annotation?
For example:
We have few custom classes: Foo; Bar. And in Main class, we entered two fields
public class Main {
Foo foo;
Bar bar;
}
I want to create annotation, which helps to initialize these fields. In final result I want to see something like this:
#Initialize
Foo foo;
#Initialize
Bar bar;
Annotation itself does nothing. It is just a metadata that can be retrieved using reflection. So, you can implement a kind of factory that receives class, creates its instance using default constructor, discovers the class's fields annotated with your annotation and sets the fields' values.
However I'd as the following questions before starting the implementation:
where will this factory find the values of foo and bar (probably from some kind of repository? Probably from JNDI?)
Do you really need this? Probably initialization using constructor is better. In this case you can mark all fields final, so you object will be immutable that have a lot of advantages
Are you probably re-inventing the wheel? Take a look on Spring framework. It does what you want and much-much more.
Related
I'm a fairly experienced programmer but I'm fairly new to Guice and I'm not sure what the best practices are. Here is my possibly flawed understanding so far, please point out if I use incorrect terminology, question follows after:
Classes with a (public) no arguments constructor or an #Inject-annotated constructor (there may be only one such constructor) do not need to be explicitly bound/provided in the module. Though in the latter case, of course, the constructor parameters may need to be explicitly provided unless they can also be auto-provided by the same rule.
When instances of such classes are (automatically) provided, this can always be thought of as being done in injector.getInstance(...) fashion – #Inject-annotated members (like say injected private fields in the class, see my Car example) will also be injected and not left null.
The above two facts(?) partially solve the problem that one can not explicitly bind/provide an instance with #Inject-annotated members, since one can not create an instance inside a provider using injector.getInstance(...) and so the #Inject-annotated members will be left null.
The remaining problem case is when the constructor requires one or more parameters to be given during creation, the values of which cannot be known up front and therefore cannot be injected.
The solution generally seems to be to provide/inject a factory with a parameterized create method to create the instances when and as needed, but this could only be done using new, which does not work in general – what if the class contains #Inject-annotated members itself? Constructing the class with new will leave those should-be-injected members null-valued.
Here is sample code:
class Car {
#Inject
private Engine engine;
...
public Car(final String cannotBeInjected) {
...
}
}
How would I make Car (or a Car factory) injectable and still allow for an Engine instance to also be injected? A possible solution is to just assign the cannotBeInjected value via some setter after creation, but this just doesn't seem elegant.
Hi I have a very simple dagger questions for android.
class Fooz {
#Inject Foo1 mFoo1;
public Fooz() {
....
}
}
class Fooz {
private Foo1 mFoo1;
#Inject public Fooz(Foo1 foo1) {
mFoo1 = foo1;
}
}
How are the two classes identical?
The first one injects Foo1 field directly while the second one assignes mFoo1 in the constructor.
For the second one, does Foo1 get injected from object graph as soon as Fooz is created and added to object graph?
If they are different, why so?
Thanks!
Constructor injection gives you more control over the object instantiation since using field injections means to restrict your class creation to reflection and rely on support to these particular injection annotations. Besides that, having the dependencies clearly on the constructor let the code easier to maintain and to test.
As far as I know, there is no difference regarding the way it is held on the dagger graph but a constructor call is always faster than injected fields.
In my opinion, we should use property only when we do not have control over the object creation, as in Activities and Fragments, per example.
These classes will behave the same when Fooz will be Injected using dependency injection. However they will behave differently when constructed using Constructor's you defined.
Example 1. Calling new Fooz() will result in mFoo1 being null.
Example 2. Calling new Fooz(foo1) will result in mFoo1 being initialized to foo1.
The preferred (personal opinion) way is to use dependency injection annotation on constructor, because it will avoid null pointer exceptions, as explained when comparing example 1 and example 2. What is more such constructor gives more flexibility when testing your classes as you can provide mocks, much easier.
These is sonarqube rule with better description, explaining what I mentioned https://sonarcloud.io/coding_rules?open=squid%3AS3306&rule_key=squid%3AS3306 .
We have application in Java, and we are using one library class. After long time after project start we got situation where, in every function we have used that class we want to add one more element in object of the class (just adding value, not adding any new member).
This change is huge. Not difficult to do, but we have used this class in 100s of functions.
Now one solution is we can inherit this class and add required change in derived class. We keep name of class same (and use fully qualified name for base class to inherit), just will change package name so we can use derived class in our code.
Is there any problem in this approach? Because my manager's suggestion is 'Its not easy as it seems to be'.
Kindly suggest if I am doing anything wrong.
Whether inheritance is the best solution depends upon the element you are trying to add. If possible consider composition over inheritance. The advantages can be found here. There you can find a example of one of the pitfall when one tries to override one of the methods. This is more possible in your case since you do not have the source code of library.
you can make small changes in the original class as long as it does not interfere with the original functioning of the class. this is better idea instead of making a derived class with the same name as base class.
If all you're adding is a single variable, this is probably safe. Anything more complicated is dangerous. I don't have any code to go on, but inheritance is probably not the right choice. What happens if you make another subclass that adds a different field, and a few months later you realize now you need both fields? Inheritance is not composable - you can't mix and match the specializations you make in subclasses. Use aggregation. If you need a Foo that also has a Bar, then make a simple container class that has both a foo and a bar:
class FooWithBar {
public final Foo foo;
public final Bar bar;
public FooWithBar(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
}
I was thinking about code structure, and thinking about setters. These used to be void methods, so why don't use some possible return value, to enable some new code structure?
My idea was to change all the properties setters from void to an instance reference, so we can do setters sequentially, or something else. Here is an example:
public class MyClass {
private int foo;
private String bar;
public MyClass setFoo(int foo) {
this.foo = foo;
return this;
}
public MyClass setBar(String bar) {
this.bar = bar;
return this;
}
}
Then in some other place in the code we could do:
...
MyClass myInstance = new MyClass();
myInstance.setFoo(auxFoo).setBar(auxBar);
...
This allow to set all of class properties in a single line, useful in transformation methods.
Or even:
...
return myInstance.setFoo(auxFoo);
This one was my goal, to be able for example to set an error property, while returning it. This can simplify a catch block, for instance.
EDIT:
After some answers I need to add:
The question is just about setters (not about doing this in all methods), and not restricted to chaining, but to other usages like the return example.
Could the change from void to something else create any problem?
JavaBeans Introspection, for instance.
Can you see any more advantage or disadvantage of doing this?
I was hoping to see some discussion.
It's a common technique, known as Method Chaining. Hibernate uses it in its Criteria classes, and is present in other popular frameworks, such as Wicket.
Generally, you've got to be careful and apply it in those void methods that you're sure that will never need to return anything. And you shouldn't be using it in your Java Beans, as it has been already discussed in this question: Does Java bean's setter permit return this?.
See this related SO question for some tips and drawbacks that may be useful while using this pattern.
This is quite common practice and definitely a pattern - not an anti-pattern. It is more commonly referred to as :
http://en.wikipedia.org/wiki/Fluent_interface
and
http://en.wikipedia.org/wiki/Method_chaining
Some excellent libraries make use of it : jQuery and joda-time.
You can also specify when the chain ends by using an end method that does not return anything, or does something else entirely - in the case of an inner static builder it calls a constructor.
For what its worth I really like it.
I think this pattern has its uses, and there's nothing inherently wrong with it.
I personally use it from time to time. There are well-established libraries using it, e.g. Gson. Even though not strictly a setter, Java's StringBuilder.append() is not dissimilar in spirit.
I would not recommend doing this as many things rely on a specific method signature for setters to allow Bean like functionality. I do not know for certain, but this may stop things like spring, or jsf, or other tech that assumes Bean-like setters.
This falls under a series of well-known and recognized patterns.
The general idea of having methods return a reference to be able to call more methods is called Method Chaining.
A more specific example of this type of method chaining is when methods are used to set properties of an instance used as input to a function. This is popular in C++ and is called the Named Parameter Idiom.
I have a hibernate POJO that I want to unit test. It looks similar to this:
public class MyPojo{
private final Integer someIntData;
private MyPojo(){
//Just to satisfy compiler, hibernate will override
someIntData = null;
}
//Methods etc...
}
I'd like to unit test this class, but don't really want to make a new constructor just to set 'someIntData' manually. Is there a quick and easy way to get hibernate to instantiate a test instance of MyPojo without mucking around with a mock database?
Private constructor means that you are either providing a "builder" method to replace the constructor (usually for immutable instances) or that the class is never meant to be initialized at all. In the later case, its usually because the class is meant to be a singleton and you'd provide a method which returns the single instance.
Hibernate does not complain about it because it uses reflection to consume this constructor. As you are not supposed to provide special code for a test, the only solution I see is to use reflection to instantiate a new POJO.
But I really think you should reconsider and provide a builder method, accepting the parameters needed to build a new instance.
What I'm going to suggest is ugly, but I think the best approach is not to use hibernate for the unit test, and use reflection to instantiate the object (which is what hibernate does internally). For example
Constructor[] cons = MyPojo.class.getDeclaredConstructors();
// Change the accessible property of the constructor.
cons[0].setAccessible(true);
MyPojo secret = (MyPojo)cons[0].newInstance(null);
Code taken from http://dunwood.blogspot.com/2004/05/instantiate-java-class-that-has.html
I remember reading that there are some frameworks that make using reflection easier for unit-tests, but I've never used them. In this type of cases, I always prefer to create a second constructor or to make the constructor package protected.
If it's a real unit test, you shouldn't need to depend on Hibernate.
It's common to change the visibility of methods, or even introduce some in order to be able to unit test a class. I wouldn't mind having a public constructor with an Integer as argument in order to unit test the POJO.
You'll certainly need to be able to set the ID in your POJOs when you'll test services anyway. For example, if you want to test that myService(MyPOJO p)calls myDAO.findFoos(p.getId()), you'll need an ID in your POJO.