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



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

i've got next 3 tests. first 2 work, lastly 1 doesn't. motivation asking question i'd able cast object a has same class object b, when a known subtype of b.

@test public void testworks() { object bar = "foobar"; string blah = (string) bar; system.out.println(blah); // outputs foobar } @test public void testalsoworks() { object bar = "helloworld"; string blah = string.class.cast(bar); system.out.println(blah); // outputs helloworld } @test public void testfails() { object bar = "foobar"; string thetype = "hello"; class stringclass = thetype.getclass(); string blah = stringclass.cast(bar); // compiler error: incompatible types: object cannot converted string system.out.println(blah); }

can explain why lastly case fails when first 2 succeed, , why case? , improve approach accomplish this?

you need specify type parameter of class:

class<string> stringclass = (class<string>) thetype.getclass();

or

class<? extends string> stringclass = thetype.getclass();

java.lang.class.cast(object obj) casts object class or interface represented class object.

without specifying type, not telling compiler class or interface represented class instance stringclass.

when phone call string.class, class object implicitly parametrized string type.

java class generics casting

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -