So I have an Interface MyInterface<T>
which has a method String save(T obj)
The implementing class has this definition Animal<T> implements MyInterface<T>
. My Main function looks like this:
MyInterface<Cow> animal = new Animal<Cow>();
Cow cow = new Cow();
cow.setName("Rose");
animal.save(cow);
So far so good, animal.save()
can only save Cows which is type-safe.
Now the problem. In my Animal class I have the save method, but before I save I want to know that my Cow has a name. The Cow class has a getName()
method.
Save method:
@Override
public void save(T obj)
What would be an apropriate way to go from T obj
to a Cow-object so I can use the member method getName()
?
My idea is:
@Override
public void save(T obj)
{
Object unknown = obj.getClass().newInstance();
if (unknown instanceof Cow)
{
String name = ((Cow) unknown).getName();
}
}
Is this "ok" java? I guess I could use reflection and search for all methods related to the unknown
object as well..
Update
As long as I define MyInterface<Cow> animal = new Animal<Cow>();
Like this I'm safe, but the problem apperas when it looks like this:
MyInterface<Object> animal = new Animal<Object>();
Then there is no getName()
method....