public static void saveTable(Object obj, int sid){}
传进来的obj对象可能是Student类型,或者是Teacher类型,
要怎么用反射获取它的类型是Studnet或者是Teacher?
而且要用反射出来的类型创建一个对象?
新手求助..
public static void saveTable(Object obj, int sid){}
传进来的obj对象可能是Student类型,或者是Teacher类型,
要怎么用反射获取它的类型是Studnet或者是Teacher?
而且要用反射出来的类型创建一个对象?
新手求助..
反射出来的是Class对象,要调用newInstance()方法可以返回Object超类对象。相应类型要进行强制类型转换.
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;
public class Reflect { public void myReflection(){ try { Class c = Class.forName("反射类路径"); //加载反射类 Constructor constructor = c.getConstructor(); //获取构造器 Object object = constructor.newInstance(); //调用无参的构造方法 创建实例 //判断object属于哪种类型 转换 if(object instanceof Student){ Student stu = (Student)object; }else{ Teacher teacher = (Teacher)object; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }