匿名内部类,比如下面函数内部
initialize定义了两个匿名类(红色代码部分):
public
synchronized
void
initialize(Environment env,
Detector detector,
DaemonListener listener,
PlainLogger[] loggers)
throws
NullPointerException,
IllegalStateException {
if
(
fInitialized
) {
return
;
}
Helper.notNull( env,
"environment"
);
Helper.notNull( detector,
"detector"
);
fDetector
= detector;
fDaemonListener
= listener;
// Check the loggers.
if
(loggers !=
null
) {
for
(
int
i = 0; i < loggers.
length
; i++) {
if
(loggers[i] !=
null
&& !loggers[i].isLoggable( )) {
throw
new
IllegalStateException(
"Logger"
+ i
+
" isn't loggable"
);
}
}
// Get loggers.
if
(loggers.
length
>= 1) {
fAppLogger
= loggers[0];
}
if
(loggers.
length
>= 2) {
fErrorLogger
= loggers[1];
}
}
// Initialize the daemon options first.
initDaemonOptions( env );
// Check the loggers.
if
(loggers !=
null
) {
for
(
int
i = 0; i < loggers.
length
; i++) {
if
(loggers[i] !=
null
&& !loggers[i].isLoggable( )) {
throw
new
IllegalStateException(
"Logger"
+ i
+
" isn't loggable"
);
}
}
// Get loggers.
if
(loggers.
length
>= 1) {
fAppLogger
= loggers[0];
}
if
(loggers.
length
>= 2) {
fErrorLogger
= loggers[1];
}
}
log(
"Using Rv Daemon: "
+
fDaemonOptions
.getCurTransportOption( ) );
// Implements a detector listener.
DetectorListener detectorListener =
new
DetectorListener( ) {
public void onConnected() {
String newDaemon = fDaemonOptions.getCurTransportOption( );
log( "Connected to Daemon: " + newDaemon );
synchronized (Daemon.this) {
fState = DaemonState.CONNECTED;
for (Iterator i = fSwitchHandlers.iterator( ); i.hasNext( );) {
((SwitchHandler) i.next( )).doSwitching( newDaemon );
}
fState = DaemonState.SWITCHED;
}
log( "Switched to Daemon: " + newDaemon );
if (fDaemonListener != null) {
fDaemonListener.onStateChanged( fState,
fLastDaemon,
newDaemon );
}
}
public void onDisconnected() {
synchronized (Daemon.this) {
fState = DaemonState.SWITCHING;
round( );
}
log( "Disconnected to Daemon: " + fLastDaemon );
if (fDaemonListener != null) {
fDaemonListener.onStateChanged( fState,
fLastDaemon,
fDaemonOptions.peekNextAvailTransportOption( ) );
}
detect( );
}
};
fDetector
.registerDetectorListener( detectorListener );
// Do the first connecting in other thread.
Thread first = new Thread( "InitialDetector" ) {
public void run() {
detect( );
}
};
first.start( );
fInitialized
=
true
;
log(
"Daemon detecting initialized."
);
}
new DetectorListener( ){...}等价于创建一个派生自接口DectorListener的子类,然后返回该类的引用。 同样的道理,另外一个是从Thread派生并且重写了run函数,因此该类可以作为一个县城对象运行。