class T2 extens T1{....}___________________________________package lab;public class TMain { public static void main(String[] args) {
T2 t2=new T2();
T1 t1=(T1)t2;
System.out.println(" t1.class:"+t1.getClass());
}
}
结果显示 t1.class:class lab.T2我想知道,如何令到显示的结果变为 t1.class:class lab.T1 呢?
T2 t2=new T2();
T1 t1=(T1)t2;
System.out.println(" t1.class:"+t1.getClass());
}
}
结果显示 t1.class:class lab.T2我想知道,如何令到显示的结果变为 t1.class:class lab.T1 呢?
public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:
搂主没有写,T2 应该是T1的子类吧,不然编译会抱错。
大概意思就是getclass()返回的是调用这个方法的类实例的 static type,静态类型,所以即使你通过强制类型转换应该还是T2类吧。
T1 t1=new T2();
System.out.println(" t1.class:"+t1.getClass());
System.out.println(" t1.class:"+t1.getClass().getSuperclass());
public static void main(String[] args) {
T2 t2=new T2();
T1 t1=t2.clone();
System.out.println(" t1.class:"+t1.getClass());
}
} T2代码:
public class T implements Cloneable{
public Object clone()
{
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}}
用PROTOTYPE模式,这个问题很简单的解决。