-3

I've got an converting Problem in Java. How can I check if the content of my string matches the data class Integer in Java? As an example: I have a String "Integer", how can I compare if the content of my String matches the Java Type Integer (I don't want an integer data typ, I really want the class).

String value = "Integer";
Integer int_val = 123456;

I would try something like:

value.parseToInteger;

because I want to do something like that:

if(int_val.typeOf(value))
{
...
}

I want to check if it's class Integer because I want to compare my Integer like the example above. But I don't know how to convert the value of my String to a Java Class Type.

  • 1
    looks like you are attempting to implement javascript tricks in to java, this is not how it works, the string "Integer" is just a string, not a type, and you cannot check it at runtime simply because "Integer" is a String object while Integer is an Integer object, hope it makes sence – Constantin Trepadus Feb 20 '20 at 09:02
  • @Nicktar no it doesn't, but thanks – Marie_Jane98 Feb 20 '20 at 09:03
  • @ConstantinTrepadus ok thank you, that makes sense! – Marie_Jane98 Feb 20 '20 at 09:04
  • That duplicate seems to have nothing to do with this question, it is quite easy to missunderstand it. OP wants to compare if type name of some Object is equal to String. It has nothing to do with converting to Integer. – Amongalen Feb 20 '20 at 09:13

1 Answers1

2
String type = "Integer";
Object int_val = 123456;
if (int_val instanceof Integer) { }
if (int_val != null && int_val.getClass().getSimpleName().equals(type)) { }

One should avoid starting with too general/abstract solutions; as nice as it is to consider things on a more general/abstract level.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138