一、类反射//2006-05-10
String className = "eqxu.diy.ReflectedTarget"; //类名
String methodName = "testMethod"; //方法名
Class destClass = Class.forName(className);
Method method = destClass.getMethod(methodName, null);
Object params[] = new Object[0];
method.invoke(destClass.newInstance(), params);
二、Cloneable//2006-05-10
package c12;
import java.util.*;
class Int implements Cloneable
{
private int i;
public Int(int ii) { i = ii; }
public void increment() { i++; }
//public String toString()
//{
//return Integer.toString(i);
//}
public synchronized Object clone() {
try {
Int v = (Int) super.clone();
v.i = i;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
}
public class Cloning
{
public static void main(String[] args)
{
Vector v = new Vector();
for(int i = 0; i < 10; i++ )
{
Int I=new Int(i);
v.addElement((Int)I.clone());
//v.addElement(I);
System.out.println("I: " + I);
}
System.out.println("v: " + v);
Vector v2 = (Vector)v.clone();
//深层复制
for(int i = 0; i < v.size(); i++)
v2.setElementAt(
((Int)v2.elementAt(i)).clone(), i);
// Increment all v2's elements:
for(Enumeration e = v2.elements(); e.hasMoreElements(); )
{
//System.out.println("e.nextElement(): " + e.nextElement());
((Int)e.nextElement()).increment();
}
// See if it changed v's elements:
System.out.println("v2: " + v2);
}
}
Snake(int i, char x) {
c = x;
if(--i > 0)
next = new Snake(i, (char)(x + 1));
}
String s = ":" + c;
if(next != null)
s += next.toString();
public Object clone()
{
OceanReading o = null;
try {
o = (OceanReading)super.clone();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
// Must clone handles:
o.depth = (DepthReading)o.depth.clone();
o.temperature =(TemperatureReading)o.temperature.clone();
return o; // Upcasts back to Object
}
String classname=parantname;//父类的名字全称mo 是父类的一个对象
classname=childname;//子类的名字全称
P mmo=mo;//返回的对象
try
{
Class destClass=Class.forName(classname);//得到一个父类的类反射
Constructor mo_ctor = destClass.getConstructor(P.class);//子类的构造函数
mmo = (P) mo_ctor.newInstance(mo);
}
catch(Exception e)
{
e.printStackTrace();
}
return mmo;