简体   繁体   中英

Can we cast a object into a class type whose name is only known?

I have to dynamically fetch the tables whose names are available in dropdown in a jsp. Upon the selection of table name corresponding columns should be printed. For that I was running a loop in jsp and trying but is it possible to cast an object of "Object" type into a class whose class name is only known and after that using that object I have to acesss the corresponding class methods.

ex: className I got from jsp is "Book" and I have a class Book.class which has a method getName() so something like this is what I wanted:

 Object obj1 =  Class.forName(className).cast(obj);
 obj1.getName();

Here obj is the object I have got through session.

Yes you can do that but the object must belong to that class or some of its child class else it will give you a ClassCastException. You also need to pass complete path of that class mean fully qualified class name with package.

Object obj1 =  Class.forName(com.Book).cast(obj);
obj1.getName();

forName takes a String and you can't call getMethod on Object because there is no such method. Ideally you'd have an interface defining the method that's common in all the types you can select from your drop down.

If that is not an option, then there is an uglier option using reflection where you don't actually need to know the type in advance:

Class<?> clazz = Class.forName("Book");
// Object obj1 = clazz.cast(obj);
// The method getName() is undefined for the type Object

Method m = clazz.getMethod("getName");
String res = (String) m.invoke(obj);

I'd not recommend using this code as is in any production application though. You'll need quite a bit of validation and exception handling in order to make this work safely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM