java 类反射 Cloneable

一、类反射//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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值