title: How to check type of a variable in Java?
body: <p>I have seen many questions with similar title on StackOverflow but all those answers seem to suggest the <code>getClass().getSimpleName()</code> method. The problem is I don't wanna know the type of value that the variable holds, I am interested in the type of variable itself. In the following code, I want to print <code>Object</code>, not <code>String</code>:</p>
  
  <pre><code>Object ob = "Some String";
  System.out.println(ob.getClass().getSimpleName()); // prints "String"
  </code></pre>
  
  <p>Given that the type of variable would be a super type of the value that it holds, I can check if the value is <code>instanceof</code> some class. But <code>instanceof</code> will return true for all the super classes up until we reach Object in the hierarchy. Is there a way to specifically check the type of variable?</p>
  
  <p>There might not be any practical use cases for this in production code, but knowing the variable type may make generics easier to practice. Consider this method:</p>
  
  <pre><code>public static &lt;T&gt; void test (T a, T b) {
  
  }
  </code></pre>
  
  <p>We don't know what type the compiler infers when <code>test</code> is called with two different arguments. It might be helpful to print out what's <code>T</code> replaced with. We know that T is going to be replaced with the most specific type that both the arguments' type inherit from when the program is run. But if I were to print that type, I can't.</p>