Reputation: 9095
In my spring project, I add this generic class to provide to my entity classes some common methods used by all of them:
public abstract class object implements Comparable<object> {
@Override
public int compareTo(object arg0) {
// TODO Auto-generated method stub
return 0;
}
public int compareTo(object arg0, int ordem) {
// TODO Auto-generated method stub
return 0;
}
}
In the second method, I need a way to the derived class use the atribute indicated by ordem to perform the comparation (to be implemented).
By example, if the derived class is this:
public class Usuario extends object {
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name = "login")
private String login;
@Column(name = "senha")
private String senha;
@Column(name="first_name")
private String first_name;
@Column(name="last_name")
private String last_name;
@Column(name="email")
private String email;
...
}
then the value for ordem would be:
1=login, 2=senha, 3=first_name, 4=last_name, 5=email.
Anyone knows if this is possible and how to do if the answer was yes?
Upvotes: 0
Views: 46
Reputation: 7863
I would do something like this: Add an abstract method to your base class:
protected abstract Object getArgument(int ordem);
You still have to implement it in every inheriting class but you could generalize the comparison logic. The implementation for your example would look like this:
protected abstract Object getArgument(int ordem) {
switch(ordem) {
case 1: return login;
case 2: return senha;
case 3: return first_name;
case 4: return last_name;
case 5: return email;
default: throw new IllegalArgumentException("Unknown ordem " + ordem);
}
}
Upvotes: 1