1 RequestDispatcher rd = sc.getRequestDispatcher(url);
2 final ByteArrayOutputStream os = new ByteArrayOutputStream();
3 final ServletOutputStream stream = new ServletOutputStream()
4 {
5 public void write(byte[] data, int offset, int length)
6 {
7 os.write(data, offset, length);
8 }
9 public void write(int b) throws IOException
10 {
11 os.write(b);
12 }
13 };
14
15 final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
16
17 HttpServletResponse rep = new HttpServletResponseWrapper(response)
18 {
19 public ServletOutputStream getOutputStream()
20 {
21 return stream;
22 }
23 public PrintWriter getWriter()
24 {
25 return pw;
26 }
27 };
这是一个程序片断,请问,在片断的第3-8行和第17-27行中,new object后跟着{...}中写入方法
这是什么意思,希望得到详细解答
2 final ByteArrayOutputStream os = new ByteArrayOutputStream();
3 final ServletOutputStream stream = new ServletOutputStream()
4 {
5 public void write(byte[] data, int offset, int length)
6 {
7 os.write(data, offset, length);
8 }
9 public void write(int b) throws IOException
10 {
11 os.write(b);
12 }
13 };
14
15 final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
16
17 HttpServletResponse rep = new HttpServletResponseWrapper(response)
18 {
19 public ServletOutputStream getOutputStream()
20 {
21 return stream;
22 }
23 public PrintWriter getWriter()
24 {
25 return pw;
26 }
27 };
这是一个程序片断,请问,在片断的第3-8行和第17-27行中,new object后跟着{...}中写入方法
这是什么意思,希望得到详细解答
这是JAVA中的匿名内部类内部类,有时叫做嵌套类,被附加到JDK1.1及更高版本中。内部类允许一个类定义被放到另一个类定义里。内部类是一个有用的特征,因为它们允许将逻辑上同属性的类组合到一起,并在另一个类中控制一个类的可视性。有两方面的原因促使使用内部类:
(1) 我们准备实现某种形式的接口,使自己能创建和返回一个句柄。
(2) 要解决一个复杂的问题,并希望创建一个类,用来辅助自己的程序方案。同时不愿意把它公开。内部类对我们非常有用,因为利用它可对那些逻辑上相互联系的类进行分组,并可控制一个类在另一个类里的“可见性”。然而,我们必须认识到内部类与以前讲述的“合成”方法存在着根本的区别。通常,对内部类的需要并不是特别明显的,至少不会立即感觉到自己需要使用内部类。
One more point: unnamed class is not for reuse elsewhere.
The following example is provided for better understanding.// You have a class called A.
class A { public void sayHi(){ System.out.println("Hi, I am A."); }}class User {
public static void main(String[] args) {
// Case 0:use the original class A's sayHi()
new A().sayHi(); // same as : A a = new A(); a.sayHi();
// Case 1: You don't like the orginal sayHi()
// so you override A's sayHi() by using unnamed class
new A(){
public void sayHi() {System.out.println("Hi, I am unnamed A."); }
}.sayHi();
// Case 2: You don't like the orginal sayHi()
// so you create A1 to extend the A and override sayHi()
new A1().sayHi();
// Case 3: A's sayHi() is OK, but you want to add sayBye() also.
A a = new A(){
public void sayBye() { sayHi();System.out.println("Bye, I am unnamed A."); }
}.sayBye();
}
// extend the A and override sayHi()
static class A1 extends A { public void sayHi() { System.out.println("Hi, I am unnamed A1.");}}
}
// Case 3: A's sayHi() is OK, but you want to add sayBye() also.
new A(){
public void sayBye() {sayHi();System.out.println("Bye, I am unnamed A."); }
}.sayBye();