开发者

casting in an object based on an incoming string

Can this be done in Java

public <T> T[] getAttr(String s) {
    Object x = getSomething(s);
    com.class."s"[] y = (com.class."s"[]) x;
    return y;
}

I realise this is all very rough. But the basic principle can this be achieved in Java.

EDIT:

Guys I already have the object I wish return x. I just want it re开发者_JAVA技巧turned as the correct type. I.e the class version of s


get the class

Class<?> theClazz = Class.forName("com.class."+s);

create an array of the specified runtime type and length:

java.lang.reflect.Array.newInstance(theClazz, length);

You are going to have to suppress some warnings about type-safety. There is no way around that if you really want to go from Strings. Maybe pass in a Class object instead, then it can be made type-safe.


This is very type unsafe way to do this:

return (T[]) java.reflect.Array.newInstance( Class.forName( "com.class" + s, n );


This would be perfectly legal

public class Test {
    public static void main (String[] args) {

        Object o = new String("abc123");

        try {
            String s = cast(o, "java.lang.String");
            System.out.println(s);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static <T> T cast(Object o, String clazz) throws ClassNotFoundException {
        return (T) Class.forName(clazz).cast(o);
    }
}

The question is, what would you have accomplished? Nothing really. Sure, you can cast an object based on a string (Class.cast(...)), but you would still need to declare your output as a String at compile time. Difference between runtime type and compile-time type. And java is strongly typed. The compiler will not attempt to convert your string to a type, and generics are strictly compile-time.


I think this could be achieved using JAVA Reflection API, although I been coming across numerous warning to be careful using it, because it could lead to difficult to foreseen effects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜