How to set a Generic object within a standard class in Java?

karamazovbros :

Background Context:

I have a non-generic class that represents a complex 3D model. I also have a series of standard 3D geometric classes (Sphere, Cube, Cuboid) that all inherit from an abstract class so all the child classes inherit the same fields and functions. So each class needs to be able to work with the Complex 3D model class, which doesn't inherit from the abstract class (it doesn't have the need for the same fields/functions).

So I want to use all of the child classes with the complex model class. Specifically, one child class can work with complex model when needed by the user, so this will be saved as a field to this class for as long as the user needs it. The complex class will need to access fields and functions from these objects, so I thought using a generic function could apply to all the simple 3D mesh classes that have the same fields/functions.

Question

Let's say I have a non-generic class where I want a field of that class to be a generic type. I want the non-generic class to be able to handle a variety of user-created types.

I want a generic method inside the non-generic class that can set the generic field, like this:

void <T> setGenericObject(T object){
    genericField = object;
}

However, I don't know how to declare the generic field properly. I don't want to create a generic class just for one small field of it (since working with other objects is only a small part of the functionality of that class). How would I properly declare this genericField variable inside my class for this to work?

Bonfra04 :

You could declare the field to be of type Object and set it equal to the parameter. All classes in Java extend Object class, so you can use it as generic type:

private Object genericObject;

public void setGenericObject(Object object) {
    this.genericObject = object;
}

Then if you want then to invoke a method that doesn’t belong to Object, you can do so with a cast:

public void executeMethod() {
    ((ClassName) this.genericObject).methodName();
}

Be aware of ClassCastExceptions, though.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116908&siteId=1