0

So here's my situation, I have a generic class called:

public class SortsTestController<T extends Comparable<T>>

Later in the code in order to grab the correct text file, I need to check whether type T is an Integer or a String. I know in C# an easy way to do this is just to do typeOf(T), but to my dismay there seems to be no easy way to do this in Java. Since I'm relatively new to coding, could someone give me a simple work around? Every post I've found mentions type erasure and reflection n' stuff like that and doesn't give a clear solution, and I can barely follow. I just need a simple solution that works.

In case this helps here's what I'm trying to do:

if (T is an Integer)
    file += "Int.txt";
else
    file += "Str.txt";
Alex
  • 620
  • 1
  • 6
  • 20
  • Throws a can't find symbol error, I believe instanceof only works for objects that have actually been instantiated. I've used instanceof on the first element on generic lists, great way to do that in that situation, but it won't work here. – Alex May 07 '18 at 00:52
  • You would have to use `instanceof` in your generic class... – Jacob May 07 '18 at 00:53
  • I tried doing `Class type` and then assigning it in the constructor. But when I do `type instanceof Integer` it says "incompatiable types Class cannot be converted to Integer. – Alex May 07 '18 at 00:57
  • ```public class SortsTestController>{ public T myType public SortsTestController(T myType) { this.myType = myType; } public String getFileByType() { if(myType instanceof Integer) { return "Int.txt"; } //remainder of implementation here } } ``` – Jacob May 07 '18 at 01:02
  • 1
    Do `if (type == Integer.class)` or `if (Integer.class.isAssignableFrom(type))` – Erwin Bolwidt May 07 '18 at 01:02
  • Oh, I really like the first if statement, it all makes sense and works, thanks! – Alex May 07 '18 at 01:03

0 Answers0