-3

I have a scenario where i need to use "Test String" instanceof "String"

is anyway i can do that in java?

The requirement is validate string with a quoted type like "String", "Boolean"

2 Answers2

0

Based upon your question I assume you are asking a Javascript question rather than a Java question. In Java, the use of instanceof is relatively rare (and IMO, should be avoided unless absolutely necessary) since Java is a statically typed language.

In Javascript:

typeof object === 'string'

In Java:

object instanceof String
mario_sunny
  • 1,412
  • 11
  • 29
  • It's possible that the OP made this mistake, but on his profile, the most common tags are java, spring-boot, spring, and so on. Therefore I think this question is probably meant to be about Java. – kaya3 Nov 01 '19 at 20:15
0

To test this dynamically where the class name is a string:

String className = "java.lang.Integer";
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class<?> cls = loader.loadClass(className);
if(cls.isInstance(object)) {
    // ...
}

Note that you can only load a class by its binary name, so you must write "java.lang.String" instead of just "String", for example.

kaya3
  • 47,440
  • 4
  • 68
  • 97