以下接口定义展示了java.rmi.Remote接口最典型的用法:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface TimeKeeper extends Remote
{
public String currentDate() throws RemoteException;
public String currentTime() throws RemoteException;
}
由于String类声明为实现了java.io.Serializable接口,所以String是远程方法的有效返回类型。
以下代码展示了如何实现TimeKeeper接口,以便定义一个有效的远程对象:
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TimeKeeperImpl implements TimeKeeper
{
public TimeKeeperImpl()
throws RemoteException
{
}
public String currentDate() throws RemoteException
{
Calendar cal = new GregorianCalendar();
String retVal = (cal.get(Calendar.MONTH) + "/" +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
cal.get(Calendar.YEAR));
return retVal;
}
public String currentTime() throws RemoteException
{
Calendar cal = new GregorianCalendar();
String retVal = (cal.get(Calendar.HOUR_OF_DAY) + ":" +
cal.get(Calendar.MINUTE) + ":" +
cal.get(Calendar.SECOND));
return retVal;
}
}
