java - Get same field from different objects -


i want generic method in java receives object , same property no matter type of object is.

for instance: have 2 objects, car , house , know these objects have attribute id. can write such method ?

public void method(object x) {   x.getid(); }  

you cannot unless use of reflection, pretty exception-prone.

public void method(object o) throws nosuchfieldexception, securityexception {   field idfield = o.getclass().getdeclaredfield("id");   int id = idfield.getint(o); } 

but common way solve such operation using polymorphism or generic method interface.

public interface identifiable {   public int getid(); }  public <t extends identifiable> void method(t anidentifiableobject) {   anidentifiableobject.getid(); }   public void method(identifiable anidentifiableobject) {   anidentifiableobject.getid(); } 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -