今天的 Java Practice 如下, 請服用:
- Coper 類別的功用為何?
- Coper:: <T> copyInstance(T obj) 方法使用了 Java Generic 的技巧,請解釋這裡採用型別參數的好處?
- main 方法中印出的兩個 User 物件,內容是否相同? 若有差異,原因為何?
abstract class Copier {
@SuppressWarnings("unchecked")
public static <T> copyInstance(T obj) throws IOException,
ClassNotFoundException {
ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream(outBytes);
outStream.writeObject(obj);
outStream.close();
ByteArrayInputStream inBytes = new ByteArrayInputStream(outBytes
.toByteArray());
ObjectInputStream inStream = new ObjectInputStream(inBytes);
T copied = (T) inStream.readObject();
inStream.close();
return copied;
}
}
class User implements Serializable {
private static final long serialVersionUID = 1L;
private Date date = new Date();
private String username;
private transient String password;
public User(String name, String pwd) {
username = name;
password = pwd;
}
public String toString() {
String pwd = (password == null) ? "(n/a)" : password;
return "logon info: \n username: " + username
+ "\n date: " + date
+ "\n password: " + pwd;
}
}
public class CopierTest {
/**
* @param args
* @throws Exception
* @throws IOException
*/
public static void main(String[] args) throws Exception {
User jack = new User("Jack", "magic");
System.out.println(jack);
User copyOfJack = Copier.copyInstance(jack);
System.out.println(copyOfJack);
}
}
沒有留言:
張貼留言