hamed
hamed

Reputation: 8033

java - cast a non-null object to dynamic object

I have this method:

 public static Object filterObject(Object object, String objectName){
      ...
 }

And here is how to I call it:

Entity1 entity1 = new Entity1();
//Call some setters
Test.filterObject(entity1, "Entity1");

I want to cast Object into Entity1 inside of that method. How can I do this?

Edit My question is how can I convert object into an instance of objectName class?

Upvotes: 0

Views: 701

Answers (3)

VGR
VGR

Reputation: 44413

If at all possible, you should pass the actual class object:

public static <T> T filterObject(Object object, Class<T> desiredClass) {
    return desiredClass.cast(object);
}

If you really must pass a class name, you can use Class.forName:

public static Object filterObject(Object object, String className)
throws ClassNotFoundException {
    Class<?> desiredClass = Class.forName(className);
    return desiredClass.cast(object);
}

Upvotes: 1

Xtrinity
Xtrinity

Reputation: 125

You should be using generics.

For example,

public static <T> T filterObject(T object, String objectName) {
  ...
}

Entity1 entity1 = new Entity();
Test.filter(entity1, "Entity1");

By using generics you don't need to cast and can avoid ClassCastException. Basically T can be substituted with your object's type.

Additionally, you can also use the following if you want to guarantee that the object being passed is a subclass of another type.

public static <T extends ParentClass> T filterObject(T object, String objectName) {
  ...
}

EDIT: You should be using generics over casting due to the reasons stated above if you do not need a mixed bag of different types. Refer to this post for a good clarification on whether or not you should be using generics. https://stackoverflow.com/a/11402351/5085407

Upvotes: 3

Miguel Salto
Miguel Salto

Reputation: 94

As Codebender told you this is only a matter of specifying the cast:

public static Object filterObject(Object object, String objectName){
    Entity1 entity1 = (Entity1) object;
    // Your implementation here
    return entity1;
}

Another approach is using "generics", e.g.

public static <T extends Entity1> T filterObjectWithGeneric(T object, String objectName) {
    // Your implementation here
    return object;
}

Greetings.

Upvotes: 0

Related Questions