0

I have a question around the topic Generics in Java: Let's say I have following generic (static) method in class. In this method, I want to have access to certain method/fields of the real class. Is there some typesafe way in the static language Java? Or are there any workarounds?

public class GenericClassUtil {

public static <T> void  workWithRealTypeAttr(T objectClass) {
//here get access to values of Easel, Cat, Dog or some other class
}

}

In main code:

GenericClassUtil.workWithRealTypeAttr(new Easel());
GenericClassUtil.workWithRealTypeAttr(new Cat());
GenericClassUtil.workWithRealTypeAttr(new Dog());
2
  • 3
    Why not letting Easel, cat, dog implement the same interface and expose those 'certain methods' there? Aug 18, 2014 at 8:50
  • 1
    return type is not mentioned. Where is the issue?
    – Braj
    Aug 18, 2014 at 8:50

6 Answers 6

1

Create an Interface and extend Easel, Cat, Dog class to that interface.

public static <T extends ThatInterface>  workWithRealTypeAttr(T objectClass) {
//here get access to values of Easel, Cat, Dog or some other class
}

Ref:

There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

public class Box<T> {

    private T t;          

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public <U extends Number> void inspect(U u){
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}
4
  • 3
    why Generic is needed in this case? Simply use ThatInterface as method arguments.
    – Braj
    Aug 18, 2014 at 8:53
  • if you have interfaces that extend from the interface, then this is necessary in order to use both types of the interface. This gave me a headache a while ago. Aug 18, 2014 at 8:54
  • @Higune So ThatInterface contains methods specific to Bird as well as Mammal ,how? Interface should be designed for one functionality, You don't want to mix Flyable and Swim-able in one interface.
    – Braj
    Aug 18, 2014 at 9:08
  • @Higune How to call methods of real class? In this case you need to define all the methods in one interface and all the classes must provide implementation of all the methods, not relevant as well for example you need to implement Bird specific method in Mammal class as well that's not a good design.
    – Braj
    Aug 18, 2014 at 9:19
1

You can do if you limit the generic type to classes that extend a certain base class.

For example if your method only operates on Animal class then you would have:

public static <T extends Animal>  workWithRealTypeAttr(T objectClass) {
   objectClass.someAnimalMethod()
}

public class Animal {

    public void someAnimalMethod() {

    } 
}

Each one of Easel, Cat and Dog would have to extend Animal. Trying to call workWithRealTypeAttr with an argument that does not extend Animal would result in a compile time error.

You can of course offer yourself even more flexibility by using interfaces instead of classes. Generics would work in exactly the same way.

You would just have an interface Animal and the classes Easel, Cat and Dog would implement that interface.

NOTE

As @user3218114 very correctly points out, there is no need to use generics in this simple case. You can just go with Animal as an argument to workWithRealTypeAttr. But I did not post that answer because I wanted to show OP how generics can work in the case he/she presented. The solution would obviously be more applicable if the method worked on Collection or something else that could take full advantage of generics.

4
  • 2
    what Gerenic will do here. Simply pass Animal as method arguments.
    – Braj
    Aug 18, 2014 at 8:55
  • You are correct of course, but what I was trying to show is how you can generally work with generics in the fashion that the OP wants. If I just used the Animal class or interface, OP would not get the understand generics like he is trying to
    – geoand
    Aug 18, 2014 at 8:57
  • I will add a note to the answer.
    – geoand
    Aug 18, 2014 at 8:59
  • We can further groups animals as suggested in my post because Animal is more generic class that don't have all the methods specific to bird and mammal.
    – Braj
    Aug 18, 2014 at 9:06
1

I want to have access to certain method/fields of the real class

If you want to access method/fields of the real class then use different overloaded methods

class GenericClassUtil {

    public static void workWithRealTypeAttr(Bird objectClass) {
          // call a method specific to Bird (Easel)
    }
    
    public static void workWithRealTypeAttr(Mammal objectClass) {
     // call a method specific to Mammal (Cat, Dog etc)
    }
} 

You can groups classes as Mammal, Bird and make the method more generic.

enter image description here


You can group classes based on behavior as per design pattern.

class GenericClassUtil {

    public static void workWithRealTypeAttr(Flyable objectClass) {
          // call a method specific to Flyable 
    }
    
    public static void workWithRealTypeAttr(Swimmable objectClass) {
     // call a method specific to Swimmable 
    }
} 

interface Swimmable { public void swim() }
interface Flyable   { public void fly()  }

enter image description here

It's better explained in Head First Design Pattern

1
  • This feels similar to the Visitor pattern. Aug 18, 2014 at 8:55
0

The only way you can do is let all your classes implements a common interface and keep one common method in that interface.

And you have to specify bounds for your T like (Considering Animal is the super class for all your mentioned class)

Then you can access t.commonMethod() inside

For example Have interface like

public interface Animal {
    void commonMethod();
}

Inside your method

<T extends Animal> tryWithGenerics(T t) {
    t.commonMethod(): //call like this
}

Note : All your classes should implement that Animal interface

0

Yes you can.

There are two (or more) ways to achieve it.

You can use Animal interface/class and use wildcard like this:

public static <T extends Animal> void makeAnimalEat(T animal) {
    animal.eat();
}

or use reflection like this:

public static <T> void makeAnimalEatReflection(T animal) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    animal.getClass().getMethod("eat").invoke(animal);
} 

Where Animal is interface:

interface Animal{
    void eat();
}

For additional information about generic and wildcards you can visit http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

0

Although it's not elegant you could use construction as below. You can try using instanceof and casting.

public static <T>  workWithRealTypeAttr(T objectClass) {
    if (objectClass instanceof Easel) {
        ((Easel) objectClass).toSomehtingEaselsDo());
    } elseif (objectClass instanceof Cat) {
        ((Cat) objectClass).toSomehtingCatsDo());
    } elseif (objectClass instanceof Dog) {
        ((Dog) objectClass).toSomehtingDogsDo());
    } else {
        //do something to inform about not supported class.
    }
}

The other way may be using a common interface (as suggested in other answers) <T extends yourInterface> or a Decorator pattern.

2
  • this looks really bad. Aug 18, 2014 at 8:53
  • I know it's not elegant. But it works. Plus in question a 'class specyfic methods' where requested, so using common interface is not a solution. Aug 18, 2014 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.