Reputation:
There's the following class:
public abstract class AbstractWriter<T extends BE> {
protected final T be;
// Constructor, some methods
public static interface Setter {
void setNewValue();
}
protected <S> void setValue(final Class<S> clazz, final S oldValue,
final S newValue, final Setter setter) {
// Do something
setter.setNewValue();
// Do something
}
}
Then there's PersonWriter
, which extends AbstractWriter
and looks currently like this:
public class PersonWriter extends AbstractWriter<BEPerson> {
public PersonWriter(BEPerson be) {
super(be);
}
public void setName(String oldValue, final String newValue) {
setValue(String.class, oldValue, newValue, new Setter() {
@Override
public void setNewValue() {
be.setName(newValue);
}
});
};
}
But I want setName
to look like this:
public void setName(String oldValue, String newValue) {
setValue(String.class, oldValue, newValue, new Setter() {
@Override
public void setNewValue(String newValue) {
be.setName(newValue);
}
});
};
How do I have to modify AbstractWriter
, to make it work (if it's even possible)?
Upvotes: 2
Views: 731
Reputation: 28761
Is this what you are looking for?
class BE {
}
class BEPerson extends BE {
void setName(String s) {}
void setAge(Integer i) {}
}
public abstract class AbstractWriter<T extends BE> {
protected final T be;
// Constructor, some methods
AbstractWriter(T be) { this.be = be; }
public static interface Setter<S> {
void setNewValue(S v);
}
protected <S> void setValue(final Class<S> clazz, final S oldValue,
final S newValue, final Setter setter) {
// Do something
setter.setNewValue(newValue);
// Do something
}
}
class PersonWriter extends AbstractWriter<BEPerson> {
public PersonWriter(BEPerson be) {
super(be);
}
public void setName(String oldValue, final String newValue) {
setValue(String.class, oldValue, newValue, new Setter<String>() {
@Override
public void setNewValue(String newValue) {
be.setName(newValue);
}
});
};
public void setAge(Integer oldValue, final Integer newValue) {
setValue(Integer.class, oldValue, newValue, new Setter<Integer>() {
@Override
public void setNewValue(Integer newValue) {
be.setAge(newValue);
}
});
};
}
Upvotes: 0
Reputation: 4340
You seem to be going a rather long way to call a setter function on a field ;-). How is the new Setter()
in the setValue
call you want to have supposed to know when newValue
is a String
and when it is something else?
With a type parameter for setter, I think it should not be difficult:
public abstract class AbstractWriter<T extends BE> {
//...
public static interface Setter<S> {
void setNewValue(S newValue);
}
protected <S> void setValue(final Class<S> clazz, final S oldValue,
final S newValue, final Setter<S> setter) {
// Do something
setter.setNewValue(newValue);
// Do something
}
}
Upvotes: 1