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 You need to specify the type parameter for or Without specifying the type, you are not telling the compiler what class or interface 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?
class :
class & lt; String & gt; String class = (class
class
java.lang.Class.cast (object obj) class object casts an object for the class or interface represented by the object.
class example
stringclass .
string type
Comments
Post a Comment