简体   繁体   中英

How do you call a method of a generic type in java?

I am trying to make a method which takes in a variable object type as a parameter, and then updates a database depending on what object was passed, a bit like how Petapoco works for C#. For this I am trying to use a generic method in which the object that is passed passes a number of checks before it is inserted/updated into its relevant table. A number of questions on Stack Overflow point me towards using a method signature like this:

public <T> void upsertObject(Class<T> objectClass, T actualObject) { }

Within the method I would like to be able to call methods like actualObject.getId() but the compiler needs to know the actual type of the object to call its relevant methods. Is there any way around this? How would I go about achieving these calls?

EDIT:

Edited for more clarity

After adding an interface with which to bind T, I found I was getting the error:

"Cannot make a static reference to the non-static method getId() from the type CycleComponent"

The method now looks like this, the error line is under T.getId()

public <T extends CycleComponent> void upsertObject(Class<T> objectClass, T fitProObject) {
    if (objectClass.getName() == "Cycle") {
        if (isInserted(T.getId(), "Cycles")) {
            // update the database
        }else {
            // insert into the database
        }
    }

}

The interface looks like:

public interface CycleComponent {

    String getId();

}

And the method in the Cycle class looks like:

public String getId() {
    return this.cycleId;
}

You can do it with generic type bounds.

Define:

public <T extends SomeType> void upsertObject(Class<T> objectClass, T actualObject) { }

Where SomeType is a class or interface, and you'll be able to call methods of SomeType on the actualObject instance.

This would limit this method to being used only with types that extend SomeType (if it's a class) or implement SomeType (if it's an interface).

For example:

public interface SomeType {
    String getId();
}

And:

public <T extends SomeType> void upsertObject(Class<T> objectClass, T actualObject) {
    if (actualObject.getId() != null) {
       ...
    }
}

Assuming this doesn't have to be absolutely generic (for example, it probably doesn't make sense to upsert a java.lang.Integer , right?), I'd define an interface with all the methods you need, and add that to the generic classification:

public interface Upsertable {
    int getID();

    // Other methods you may need...
}

public <T extends Upsertable> void upsertObject(Class<T> objectClass, T actualObject) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM