java - Why does casting based on Class.class work but not getClass? -


I have the following 3 tests: The first two works, the last one does not. My motivation for asking this question is that I want to be able to cast the object A so that the object B , when A B is known as a sub-type of .

  @Test Public Zero Testworks () {Object Bar = "Fobar"; String Blow = (string) bar; Println (blah); // Output Fobre} @Test Public Zero TestAlosOverseSquare () {Object Bar = "Hellkollwald"; String blah = string.class.val (bar); Println (blah); // outputs helloworld} @Test Public Zero TestFile () {Object Bar = "Fubar"; String thetype = "hello"; Class string class = thetype.getClass (); String blah = string class.cast (bar); // Compiler Error: Incompatible Type: Object can not be converted to string system. Out.println (blah); } Can anyone explain that when the first two succeeded, and why is this the case, why have they finally failed? And what would be a better approach to achieving this?   

You need to specify the type parameter for class :

  class & lt; String & gt; String class = (class   

or

  class   

java.lang.Class.cast (object obj) class object casts an object for the class or interface represented by the object.

Without specifying the type, you are not telling the compiler what class or interface class example stringclass .

string type

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -