﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-【永恒的瞬间】  -文章分类-java_code</title><link>http://www.blogjava.net/19851985lili/category/19706.html</link><description>☜GivE mE HapPy ☞




</description><language>zh-cn</language><lastBuildDate>Wed, 25 Apr 2007 18:59:24 GMT</lastBuildDate><pubDate>Wed, 25 Apr 2007 18:59:24 GMT</pubDate><ttl>60</ttl><item><title>請問在JSP如何取得上一頁網址</title><link>http://www.blogjava.net/19851985lili/articles/113635.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Wed, 25 Apr 2007 13:57:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/113635.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/113635.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/113635.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/113635.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/113635.html</trackback:ping><description><![CDATA[<pre><font class=java-reserved_word><strong>import</strong></font> java.io.IOException;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.*;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.http.*;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.Filter;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.FilterChain;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.FilterConfig;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.ServletException;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.ServletRequest;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.ServletResponse;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.http.Cookie;
<font class=java-reserved_word><strong>import</strong></font> javax.servlet.UnavailableException;
<font class=java-reserved_word><strong>import</strong></font> java.sql.*;
<font class=java-reserved_word><strong>import</strong></font> javax.sql.*;
<font class=java-reserved_word><strong>import</strong></font> javax.naming.*;
&nbsp;
<font class=java-reserved_word><strong>public</strong></font> <font class=java-reserved_word><strong>class</strong></font> LogFilter <font class=java-reserved_word><strong>extends</strong></font> HttpServlet <font class=java-reserved_word><strong>implements</strong></font> Filter
<font class=java-bracket>{</font>
<font class=java-reserved_word><strong>protected</strong></font> FilterConfig filterConfig = <font class=java-reserved_word><strong>null</strong></font>;
Connection cn =<font class=java-reserved_word><strong>null</strong></font>;
DataSource ds = <font class=java-reserved_word><strong>null</strong></font>;
Context ctx = <font class=java-reserved_word><strong>null</strong></font>;
&nbsp;
<font class=java-reserved_word><strong>public</strong></font> <font class=java-reserved_word><strong>void</strong></font> destroy()
<font class=java-bracket>{</font>
<font class=java-bracket>}</font>
<font class=java-reserved_word><strong>public</strong></font> <font class=java-reserved_word><strong>void</strong></font> doFilter(ServletRequest req, ServletResponse res, FilterChain chain) <font class=java-reserved_word><strong>throws</strong></font> IOException, ServletException
<font class=java-bracket>{</font>
String clientIPAddress = req.getRemoteAddr();<font class=java-comment>//取得IP</font>
String path= ((HttpServletRequest)req).getRequestURI();<font class=java-comment>//取得路徑</font>
String prg=path.substring(path.lastIndexOf(<font class=java-string>"/"</font>)+1);<font class=java-comment>//取得程式名稱</font>
String which=((HttpServletRequest)req).getQueryString();<font class=java-comment>//查詢字串</font>
String cookiename=<font class=java-reserved_word><strong>null</strong></font>;
String cookievalue=<font class=java-reserved_word><strong>null</strong></font>;
<font class=java-comment>//將path存入Cookie，ErrorPage用！</font>
Cookie[] allcookie = ((HttpServletRequest)req).getCookies();
<font class=java-reserved_word><strong>int</strong></font> i=0;
<font class=java-reserved_word><strong>if</strong></font> (allcookie.length&gt;0)
<font class=java-bracket>{</font>
<font class=java-reserved_word><strong>while</strong></font>(i&lt;=allcookie.length)
<font class=java-bracket>{</font>
cookiename=allcookie[i].getName();
cookievalue=allcookie[i].getName();
<font class=java-reserved_word><strong>if</strong></font> (cookiename.equals(<font class=java-string>"URI"</font>))
<font class=java-reserved_word><strong>break</strong></font>;
i++;
<font class=java-bracket>}</font>
<font class=java-bracket>}</font>
<font class=java-reserved_word><strong>if</strong></font> (cookiename.equals(<font class=java-string>"URI"</font>))
<font class=java-bracket>{</font>
<font class=java-reserved_word><strong>if</strong></font>(path != <font class=java-string>"ErrPage.jsp"</font>)
allcookie[i].setValue(path);
<font class=java-bracket>}</font>
<font class=java-reserved_word><strong>else</strong></font>
<font class=java-bracket>{</font>
Cookie CURI = <font class=java-reserved_word><strong>new</strong></font> Cookie(<font class=java-string>"URI"</font>,path);
((HttpServletResponse)res).addCookie(CURI);
<font class=java-bracket>}</font>
<font class=java-reserved_word><strong>try</strong></font>
<font class=java-bracket>{</font>
&nbsp;
ctx = <font class=java-reserved_word><strong>new</strong></font> InitialContext();
ds = (DataSource)ctx.lookup(<font class=java-string>"java:comp/env/jdbc/csc"</font>);
cn = ds.getConnection();
PreparedStatement st = cn.prepareStatement(<font class=java-string>"INSERT INTO system_log_info (user_ip, datetime, place, act, which) VALUES (?,?,?,?,?)"</font>);
st.setString(1,clientIPAddress);
st.setString(2,cscBean.common.datetime.getNowDate());
st.setString(3,path);
st.setString(4,prg);
st.setString(5,which);
st.executeUpdate();
st.close();
cn.close();
<font class=java-bracket>}</font>
<font class=java-reserved_word><strong>catch</strong></font>(Exception e)
<font class=java-bracket>{</font>
e.printStackTrace();
<font class=java-bracket>}</font>
chain.doFilter(req, res);
<font class=java-bracket>}</font>
<font class=java-reserved_word><strong>public</strong></font> <font class=java-reserved_word><strong>void</strong></font> init(FilterConfig filterConfig) <font class=java-reserved_word><strong>throws</strong></font> ServletException
<font class=java-bracket>{</font>
this.filterConfig = filterConfig;
<font class=java-bracket>}</font>
<font class=java-bracket>}</font>
</pre>
<img src ="http://www.blogjava.net/19851985lili/aggbug/113635.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-04-25 21:57 <a href="http://www.blogjava.net/19851985lili/articles/113635.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>java操作excel（HSSF样式一）</title><link>http://www.blogjava.net/19851985lili/articles/113599.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Wed, 25 Apr 2007 11:18:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/113599.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/113599.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/113599.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/113599.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/113599.html</trackback:ping><description><![CDATA[<p><font size=2>import java.io.IOException;<br>import java.io.PrintWriter;<br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.Iterator;<br>import java.util.List;</font></p>
<p><font size=2>import javax.servlet.ServletException;<br>import javax.servlet.ServletOutputStream;<br>import javax.servlet.http.HttpServlet;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;</font></p>
<p><font size=2>import org.apache.poi.hssf.usermodel.HSSFCell;<br>import org.apache.poi.hssf.usermodel.HSSFCellStyle;<br>import org.apache.poi.hssf.util.HSSFColor;<br>import org.apache.poi.hssf.util.Region;<br>import org.apache.poi.hssf.usermodel.HSSFFont;<br>import org.apache.poi.hssf.usermodel.HSSFRow;<br>import org.apache.poi.hssf.usermodel.HSSFSheet;<br>import org.apache.poi.hssf.usermodel.HSSFWorkbook;</font></p>
<p><font size=2></font></p>
<p><font size=2>HSSFCellStyle类代表一种单元格样式。可以通过这些类来设置单元格的边框样式、背景颜色、字体、水平和垂直方式的对齐。<br>如:<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFWorkbook workbook = new HSSFWorkbook();&nbsp;&nbsp;&nbsp; //建立一个工作薄<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFCellStyle titleStyle=workbook.createCellStyle();&nbsp;&nbsp;&nbsp;&nbsp; //在工作薄的基础上建立一个样式<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleStyle.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);&nbsp;&nbsp;&nbsp; //设置边框样式<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleStyle.setBorderLeft((short)1);&nbsp;&nbsp;&nbsp;&nbsp; //左边框<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleStyle.setBorderRight((short)1);&nbsp;&nbsp;&nbsp; //右边框<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);&nbsp;&nbsp;&nbsp; //顶边框<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);&nbsp;&nbsp;&nbsp; //填充的背景颜色<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);&nbsp;&nbsp;&nbsp; //填充图案</font></p>
<p><font size=2>假设什么定义了一个样式，想在填充第一个单元格的时候填充红，第二格单元格填充蓝色。<br>如果:<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFCellStyle cellStyle = workbook.createCellStyle();&nbsp;&nbsp;&nbsp; //创建一个样式</font></p>
<p><font size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cellStyle.setFillForegroundColor(HSSFColor.RED.index);&nbsp;&nbsp;&nbsp; //设置颜色为红色<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);</font></p>
<p><font size=2>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFCell cell1 = row.createCell((short)1);&nbsp;&nbsp;&nbsp;&nbsp; //给单元格cell1填充红色<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell1.setCellStyle(cellStyle);</font></p>
<p><font size=2>若:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cellStyle.setFillForegroundColor(HSSFColor.BLUE.index);&nbsp;&nbsp;&nbsp; //设置颜色为蓝色<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HSSFCell cell2 = row.createCell((short)2);&nbsp;&nbsp;&nbsp; //给单元格cell2填充蓝色<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell2.setCellStyle(cellStyle);</font></p>
<p><font size=2>这个时候会出现的现象是单元格cell1和cell2都变成了蓝色。遇到这种情况，要预先定义两种不同的单元格样式。</font></p>
<p><br><font size=2>当一个EXCEL文件同时需要很多大同小异的单元格样式时，这样一一定义很麻烦。POI HSSF提供了一个HSSFCellUtil类（在org.apache.poi.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hssf.usermodel.contrib包），里面有几个方法可以绕过HSSFCellStyle直接设定单元格的样式，但这几个方法会抛出NestableException异&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 常，要处理这个异常，需要引用Apache的几个Common包：<br>commons-beanutils.jar<br>commons-beanutils-bean-collections.jar<br>commons-beanutils-core.jar<br>commons-lang.jar<br>commons-logging-api.jar</font></p>
<p><font size=2>以下是其他各种情况的处理：<br>1、中文处理：<br>要在通过POI生成的EXCEL中正常显示中文，需要为单元格设置编码：<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell.setEncoding(HSSFCell.ENCODING_UTF_16); <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellValue("部门");</font></p>
<p><font size=2>2、合并单元格：<br>HSSFSheet.addMergedRegion(new Region())方法可以合并单元格，Region()中的一个构造函数含有四个参数，分别代表起始行、起始列、结束&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 行、结束列：<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sheet.addMergedRegion(new Region(initRow, (short)(initCol-2), initRow + lists.size() - 1, (short)(initCol-2)));</font></p>
<p><font size=2>3、公式的处理：<br>HSSFCell.setCellFormula()方法用来在EXCEL单元格中写入公式。<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell = row.createCell((short)(dataFlag));<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellFormula("SUM(" + getColLetter(initCol) + (listFlag+1) +":" + getColLetter(dataFlag-1) + (listFlag+1) +&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ")");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellStyle(nameStyle);</font></p>
<p><font size=2>4、链接的处理：<br>在POI中往单元格中写链接，是用HYPERLINK函数搞定的。<br>HYPERLINK函数包含两个参数，第一个参数是指向的URL地址，第二个参数是显示字串。<br>&nbsp;&nbsp;&nbsp;&nbsp; cell = row.createCell((short)(dataFlag));<br>&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);<br>&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellFormula("HYPERLINK(\"</font><a href='http://www.xxxxx.com/xxx.jsp?id=1 ", "homepage'><font color=#0000ff size=2>http://www.xxxxx.com/xxx.jsp?id=1\",\"homepage\</font></a><font size=2>")");<br>&nbsp;&nbsp;&nbsp;&nbsp; cell.setCellStyle(linkStyle); <br>为了使链接效果更好，我们可以给链接所在单元格定义一种样式，使链接显示为有下划线的蓝色字串：<br>&nbsp;&nbsp;&nbsp; HSSFCellStyle linkStyle = workbook.createCellStyle();<br>&nbsp;&nbsp;&nbsp; linkStyle.setBorderBottom((short)1);<br>&nbsp;&nbsp;&nbsp; linkStyle.setBorderLeft((short)1);<br>&nbsp;&nbsp;&nbsp; linkStyle.setBorderRight((short)1);<br>&nbsp;&nbsp;&nbsp; linkStyle.setBorderTop((short)1);<br>&nbsp;&nbsp;&nbsp; linkStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);<br>&nbsp;&nbsp;&nbsp; linkStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);<br>&nbsp;&nbsp;&nbsp; HSSFFont font = workbook.createFont();<br>&nbsp;&nbsp;&nbsp; font.setFontName(HSSFFont.FONT_ARIAL);<br>&nbsp;&nbsp;&nbsp; font.setUnderline((byte)1);<br>&nbsp;&nbsp;&nbsp; font.setColor(HSSFColor.BLUE.index);<br>&nbsp;&nbsp;&nbsp; linkStyle.setFont(font);</font></p>
<p><font size=2>关于代码对应的颜色如下：</font></p>
<p><img class=blogimg src="file:///E:/java操作excel（HSSF样式一）_学而时习之,不亦悦乎.files/8f196ffbe882b9156d22eb96.jpg" width=911 border=0 small="0"></p>
<img src ="http://www.blogjava.net/19851985lili/aggbug/113599.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-04-25 19:18 <a href="http://www.blogjava.net/19851985lili/articles/113599.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java 如何取得环境变量</title><link>http://www.blogjava.net/19851985lili/articles/110332.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Fri, 13 Apr 2007 00:42:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/110332.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/110332.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/110332.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/110332.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/110332.html</trackback:ping><description><![CDATA[&nbsp;Java中获取JVM环境变量是很简单的，下面两句就打印出了所有的JVM环境变量：<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Properties p = System.getProperties();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p.list(System.out);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果想获得指定Key的值，则可以这样：System.getProperty(key);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 但如果想获取系统环境变量，就要想别的办法了。下面的代码可以实现：
<p>package com.zhj.tools;</p>
<p>import java.io.BufferedReader;<br>import java.io.IOException;<br>import java.io.InputStreamReader;<br>import java.util.Properties;</p>
<p>/**<br>* 文件名：GetProperty.java<br>* 描述： 取得当前系统变量的程序。<br>*&nbsp;&nbsp;&nbsp; java中的System.getProperty只是针对JVM来的，如果要取得系统环境变量，还要用到系统相关的函数。本程序先从JVM中取Key对应的Value，如果取不到再取系统环境变量<br>* 作者： 翟海军<br>*/<br>public class GetProperty {</p>
<p>/**<br>&nbsp;&nbsp; * @param args<br>&nbsp;&nbsp; * @throws IOException <br>&nbsp;&nbsp; */<br>public static void main(String[] args) throws IOException {<br>&nbsp;&nbsp; // TODO Auto-generated method stub<br>&nbsp;&nbsp; String key=null;<br>&nbsp;&nbsp; if (args.length&gt;0) key=args[0];<br>&nbsp;&nbsp; String s=getProperty(key);<br>&nbsp;&nbsp; System.out.println(s);<br>&nbsp;&nbsp;<br>}<br><br>public static String getProperty(String key) throws IOException{<br>&nbsp;&nbsp; String value=null;<br>&nbsp;&nbsp; Properties pp = null;<br>&nbsp;&nbsp; if (key == null || key.length()&lt;1) {<br>&nbsp;&nbsp;&nbsp; pp = System.getProperties();<br>&nbsp;&nbsp;&nbsp; System.out.println("未指定key，现列出所有JVM环境变量：");<br>&nbsp;&nbsp;&nbsp; pp.list(System.out);<br>&nbsp;&nbsp;&nbsp; value="未指定key，上面是所有JVM环境变量：";<br>&nbsp;&nbsp;&nbsp; return value;<br>&nbsp;&nbsp; } else {<br>&nbsp;&nbsp;&nbsp; String s = null;<br>&nbsp;&nbsp;&nbsp; value = System.getProperty(key);<br>&nbsp;&nbsp;&nbsp; if (s == null) {<br>&nbsp;&nbsp;&nbsp;&nbsp; String OS = System.getProperty("os.name").toLowerCase();<br>&nbsp;&nbsp;&nbsp;&nbsp; Process p = null;<br>&nbsp;&nbsp;&nbsp;&nbsp; if (OS.indexOf("windows") &gt; -1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p = Runtime.getRuntime().exec("cmd /c set"); // Windows系列<br>&nbsp;&nbsp;&nbsp;&nbsp; } else if (OS.indexOf("linux") &gt; -1 || OS.indexOf("aix") &gt; -1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; || OS.indexOf("unix") &gt; -1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p = Runtime.getRuntime().exec("/bin/sh -c set"); // Unix系列<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; BufferedReader br = new BufferedReader(new InputStreamReader(p<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .getInputStream()));<br>&nbsp;&nbsp;&nbsp;&nbsp; String line;<br>&nbsp;&nbsp;&nbsp;&nbsp; while ((line = br.readLine()) != null) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int i = line.indexOf("=");<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (i &gt; -1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(key.equalsIgnoreCase(line.substring(0, i))){<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; value = line.substring(i + 1);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;&nbsp; } <br>&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp; }<br>&nbsp;&nbsp; return value;<br>}</p>
<p>}<br></p>
<img src ="http://www.blogjava.net/19851985lili/aggbug/110332.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-04-13 08:42 <a href="http://www.blogjava.net/19851985lili/articles/110332.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java反射经典实例 Java Reflection Cookbook (初级) </title><link>http://www.blogjava.net/19851985lili/articles/97638.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Fri, 02 Feb 2007 12:28:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/97638.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/97638.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/97638.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/97638.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/97638.html</trackback:ping><description><![CDATA[
		<div class="postbody">Java提供了一套机制来动态执行方法和构造方法，以及数组操作等，这套机制就叫——反射。反射机制是如今很多流行框架的实现基础，其中包括Spring、Hibernate等。原理性的问题不是本文的重点，接下来让我们在实例中学习这套精彩的机制。<br /><br />1. 得到某个对象的属性<br /><br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)">1</span> <span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object getProperty(Object owner, String fieldName) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br /></span><span style="COLOR: rgb(0,128,128)">2</span> <span style="COLOR: rgb(0,0,0)">    Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> owner.getClass();<br /></span><span style="COLOR: rgb(0,128,128)">3</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">4</span> <span style="COLOR: rgb(0,0,0)">    Field field </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getField(fieldName);<br /></span><span style="COLOR: rgb(0,128,128)">5</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">6</span> <span style="COLOR: rgb(0,0,0)">    Object property </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> field.get(owner);<br /></span><span style="COLOR: rgb(0,128,128)">7</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">8</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> property;<br /></span><span style="COLOR: rgb(0,128,128)">9</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br />Class ownerClass = owner.getClass()：得到该对象的Class。<br /><br />Field field = ownerClass.getField(fieldName)：通过Class得到类声明的属性。<br /><br />Object property = field.get(owner)：通过对象得到该属性的实例，如果这个属性是非公有的，这里会报IllegalAccessException。<br /><br /><br /><br />2. 得到某个类的静态属性<br /><br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)"> 1</span> <span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object getStaticProperty(String className, String fieldName)<br /></span><span style="COLOR: rgb(0,128,128)"> 2</span> <span style="COLOR: rgb(0,0,0)">            </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br /></span><span style="COLOR: rgb(0,128,128)"> 3</span> <span style="COLOR: rgb(0,0,0)">    Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> Class.forName(className);<br /></span><span style="COLOR: rgb(0,128,128)"> 4</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 5</span> <span style="COLOR: rgb(0,0,0)">    Field field </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getField(fieldName);<br /></span><span style="COLOR: rgb(0,128,128)"> 6</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 7</span> <span style="COLOR: rgb(0,0,0)">    Object property </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> field.get(ownerClass);<br /></span><span style="COLOR: rgb(0,128,128)"> 8</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 9</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> property;<br /></span><span style="COLOR: rgb(0,128,128)">10</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br /><br />Class ownerClass = Class.forName(className) ：首先得到这个类的Class。<br /><br />Field field = ownerClass.getField(fieldName)：和上面一样，通过Class得到类声明的属性。<br /><br />Object property = field.get(ownerClass) ：这里和上面有些不同，因为该属性是静态的，所以直接从类的Class里取。<br /><br /><br />3. 执行某对象的方法<br /><br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)"> 1</span> <span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object invokeMethod(Object owner, String methodName, Object[] args) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br /></span><span style="COLOR: rgb(0,128,128)"> 2</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 3</span> <span style="COLOR: rgb(0,0,0)">    Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> owner.getClass();<br /></span><span style="COLOR: rgb(0,128,128)"> 4</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 5</span> <span style="COLOR: rgb(0,0,0)">    Class[] argsClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">new</span><span style="COLOR: rgb(0,0,0)"> Class[args.length];<br /></span><span style="COLOR: rgb(0,128,128)"> 6</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 7</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">for</span><span style="COLOR: rgb(0,0,0)"> (</span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> i </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,0)">0</span><span style="COLOR: rgb(0,0,0)">, j </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args.length; i </span><span style="COLOR: rgb(0,0,0)">&lt;</span><span style="COLOR: rgb(0,0,0)"> j; i</span><span style="COLOR: rgb(0,0,0)">++</span><span style="COLOR: rgb(0,0,0)">) {<br /></span><span style="COLOR: rgb(0,128,128)"> 8</span> <span style="COLOR: rgb(0,0,0)">        argsClass[i] </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args[i].getClass();<br /></span><span style="COLOR: rgb(0,128,128)"> 9</span> <span style="COLOR: rgb(0,0,0)">    }<br /></span><span style="COLOR: rgb(0,128,128)">10</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">11</span> <span style="COLOR: rgb(0,0,0)">    Method method </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getMethod(methodName, argsClass);<br /></span><span style="COLOR: rgb(0,128,128)">12</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">13</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> method.invoke(owner, args);<br /></span><span style="COLOR: rgb(0,128,128)">14</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br />Class owner_class = owner.getClass() ：首先还是必须得到这个对象的Class。<br /><br />5～9行：配置参数的Class数组，作为寻找Method的条件。<br /><br />Method method = ownerClass.getMethod(methodName, argsClass)：通过Method名和参数的Class数组得到要执行的Method。<br /><br />method.invoke(owner, args)：执行该Method，invoke方法的参数是执行这个方法的对象，和参数数组。返回值是Object，也既是该方法的返回值。<br /><br /><br />4. 执行某个类的静态方法<br /><br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)"> 1</span> <span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object invokeStaticMethod(String className, String methodName,<br /></span><span style="COLOR: rgb(0,128,128)"> 2</span> <span style="COLOR: rgb(0,0,0)">            Object[] args) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br /></span><span style="COLOR: rgb(0,128,128)"> 3</span> <span style="COLOR: rgb(0,0,0)">    Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> Class.forName(className);<br /></span><span style="COLOR: rgb(0,128,128)"> 4</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 5</span> <span style="COLOR: rgb(0,0,0)">    Class[] argsClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">new</span><span style="COLOR: rgb(0,0,0)"> Class[args.length];<br /></span><span style="COLOR: rgb(0,128,128)"> 6</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 7</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">for</span><span style="COLOR: rgb(0,0,0)"> (</span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> i </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,0)">0</span><span style="COLOR: rgb(0,0,0)">, j </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args.length; i </span><span style="COLOR: rgb(0,0,0)">&lt;</span><span style="COLOR: rgb(0,0,0)"> j; i</span><span style="COLOR: rgb(0,0,0)">++</span><span style="COLOR: rgb(0,0,0)">) {<br /></span><span style="COLOR: rgb(0,128,128)"> 8</span> <span style="COLOR: rgb(0,0,0)">        argsClass[i] </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args[i].getClass();<br /></span><span style="COLOR: rgb(0,128,128)"> 9</span> <span style="COLOR: rgb(0,0,0)">    }<br /></span><span style="COLOR: rgb(0,128,128)">10</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">11</span> <span style="COLOR: rgb(0,0,0)">    Method method </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getMethod(methodName, argsClass);<br /></span><span style="COLOR: rgb(0,128,128)">12</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">13</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> method.invoke(</span><span style="COLOR: rgb(0,0,255)">null</span><span style="COLOR: rgb(0,0,0)">, args);<br /></span><span style="COLOR: rgb(0,128,128)">14</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br /><br />基本的原理和实例3相同，不同点是最后一行，invoke的一个参数是null，因为这是静态方法，不需要借助实例运行。<br /><br /><br /><br />5. 新建实例<br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)"> 1</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 2</span> <span style="COLOR: rgb(0,0,0)"></span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object newInstance(String className, Object[] args) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br /></span><span style="COLOR: rgb(0,128,128)"> 3</span> <span style="COLOR: rgb(0,0,0)">    Class newoneClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> Class.forName(className);<br /></span><span style="COLOR: rgb(0,128,128)"> 4</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 5</span> <span style="COLOR: rgb(0,0,0)">    Class[] argsClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">new</span><span style="COLOR: rgb(0,0,0)"> Class[args.length];<br /></span><span style="COLOR: rgb(0,128,128)"> 6</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)"> 7</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">for</span><span style="COLOR: rgb(0,0,0)"> (</span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> i </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,0)">0</span><span style="COLOR: rgb(0,0,0)">, j </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args.length; i </span><span style="COLOR: rgb(0,0,0)">&lt;</span><span style="COLOR: rgb(0,0,0)"> j; i</span><span style="COLOR: rgb(0,0,0)">++</span><span style="COLOR: rgb(0,0,0)">) {<br /></span><span style="COLOR: rgb(0,128,128)"> 8</span> <span style="COLOR: rgb(0,0,0)">        argsClass[i] </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args[i].getClass();<br /></span><span style="COLOR: rgb(0,128,128)"> 9</span> <span style="COLOR: rgb(0,0,0)">    }<br /></span><span style="COLOR: rgb(0,128,128)">10</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">11</span> <span style="COLOR: rgb(0,0,0)">    Constructor cons </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> newoneClass.getConstructor(argsClass);<br /></span><span style="COLOR: rgb(0,128,128)">12</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">13</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> cons.newInstance(args);<br /></span><span style="COLOR: rgb(0,128,128)">14</span> <span style="COLOR: rgb(0,0,0)"><br /></span><span style="COLOR: rgb(0,128,128)">15</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br /><br />这里说的方法是执行带参数的构造函数来新建实例的方法。如果不需要参数，可以直接使用newoneClass.newInstance()来实现。<br /><br />Class newoneClass = Class.forName(className)：第一步，得到要构造的实例的Class。<br /><br />第5～第9行：得到参数的Class数组。<br /><br />Constructor cons = newoneClass.getConstructor(argsClass)：得到构造子。<br /><br />cons.newInstance(args)：新建实例。<br /><br /><br />6. 判断是否为某个类的实例<br /><br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)">1</span> <span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">boolean</span><span style="COLOR: rgb(0,0,0)"> isInstance(Object obj, Class cls) {<br /></span><span style="COLOR: rgb(0,128,128)">2</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> cls.isInstance(obj);<br /></span><span style="COLOR: rgb(0,128,128)">3</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br /><br /><br />7. 得到数组中的某个元素<br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,128,128)">1</span> <span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object getByArray(Object array, </span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> index) {<br /></span><span style="COLOR: rgb(0,128,128)">2</span> <span style="COLOR: rgb(0,0,0)">    </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> Array.get(array,index);<br /></span><span style="COLOR: rgb(0,128,128)">3</span> <span style="COLOR: rgb(0,0,0)">}</span></div><br /><br /><br />附完整源码：<br /><br /><div style="BORDER-RIGHT: rgb(204,204,204) 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: rgb(204,204,204) 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: rgb(204,204,204) 1px solid; WIDTH: 98%; PADDING-TOP: 4px; BORDER-BOTTOM: rgb(204,204,204) 1px solid; BACKGROUND-COLOR: rgb(238,238,238)"><!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--><span style="COLOR: rgb(0,0,255)">import</span><span style="COLOR: rgb(0,0,0)"> java.lang.reflect.Array;<br /></span><span style="COLOR: rgb(0,0,255)">import</span><span style="COLOR: rgb(0,0,0)"> java.lang.reflect.Constructor;<br /></span><span style="COLOR: rgb(0,0,255)">import</span><span style="COLOR: rgb(0,0,0)"> java.lang.reflect.Field;<br /></span><span style="COLOR: rgb(0,0,255)">import</span><span style="COLOR: rgb(0,0,0)"> java.lang.reflect.Method;<br /><br /><br /></span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br /> * Java Reflection Cookbook<br /> *<br /> * </span><span style="COLOR: rgb(128,128,128)">@author</span><span style="COLOR: rgb(0,128,0)"> Michael Lee<br /> * </span><span style="COLOR: rgb(128,128,128)">@since</span><span style="COLOR: rgb(0,128,0)"> 2006-8-23<br /> * </span><span style="COLOR: rgb(128,128,128)">@version</span><span style="COLOR: rgb(0,128,0)"> 0.1a<br /> </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br /><br /></span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">class</span><span style="COLOR: rgb(0,0,0)"> Reflection {<br />    </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 得到某个对象的公共属性<br />     *<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> owner, fieldName<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 该属性对象<br />     * </span><span style="COLOR: rgb(128,128,128)">@throws</span><span style="COLOR: rgb(0,128,0)"> Exception<br />     *<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object getProperty(Object owner, String fieldName) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br />        Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> owner.getClass();<br /><br />        Field field </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getField(fieldName);<br /><br />        Object property </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> field.get(owner);<br /><br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> property;<br />    }<br /><br />    </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 得到某类的静态公共属性<br />     *<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> className   类名<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> fieldName   属性名<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 该属性对象<br />     * </span><span style="COLOR: rgb(128,128,128)">@throws</span><span style="COLOR: rgb(0,128,0)"> Exception<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object getStaticProperty(String className, String fieldName)<br />            </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br />        Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> Class.forName(className);<br /><br />        Field field </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getField(fieldName);<br /><br />        Object property </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> field.get(ownerClass);<br /><br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> property;<br />    }<br /><br /><br />    </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 执行某对象方法<br />     *<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> owner<br />     *            对象<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> methodName<br />     *            方法名<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> args<br />     *            参数<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 方法返回值<br />     * </span><span style="COLOR: rgb(128,128,128)">@throws</span><span style="COLOR: rgb(0,128,0)"> Exception<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object invokeMethod(Object owner, String methodName, Object[] args)<br />            </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br /><br />        Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> owner.getClass();<br /><br />        Class[] argsClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">new</span><span style="COLOR: rgb(0,0,0)"> Class[args.length];<br /><br />        </span><span style="COLOR: rgb(0,0,255)">for</span><span style="COLOR: rgb(0,0,0)"> (</span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> i </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,0)">0</span><span style="COLOR: rgb(0,0,0)">, j </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args.length; i </span><span style="COLOR: rgb(0,0,0)">&lt;</span><span style="COLOR: rgb(0,0,0)"> j; i</span><span style="COLOR: rgb(0,0,0)">++</span><span style="COLOR: rgb(0,0,0)">) {<br />            argsClass[i] </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args[i].getClass();<br />        }<br /><br />        Method method </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getMethod(methodName, argsClass);<br /><br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> method.invoke(owner, args);<br />    }<br /><br /><br />      </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 执行某类的静态方法<br />     *<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> className<br />     *            类名<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> methodName<br />     *            方法名<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> args<br />     *            参数数组<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 执行方法返回的结果<br />     * </span><span style="COLOR: rgb(128,128,128)">@throws</span><span style="COLOR: rgb(0,128,0)"> Exception<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object invokeStaticMethod(String className, String methodName,<br />            Object[] args) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br />        Class ownerClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> Class.forName(className);<br /><br />        Class[] argsClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">new</span><span style="COLOR: rgb(0,0,0)"> Class[args.length];<br /><br />        </span><span style="COLOR: rgb(0,0,255)">for</span><span style="COLOR: rgb(0,0,0)"> (</span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> i </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,0)">0</span><span style="COLOR: rgb(0,0,0)">, j </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args.length; i </span><span style="COLOR: rgb(0,0,0)">&lt;</span><span style="COLOR: rgb(0,0,0)"> j; i</span><span style="COLOR: rgb(0,0,0)">++</span><span style="COLOR: rgb(0,0,0)">) {<br />            argsClass[i] </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args[i].getClass();<br />        }<br /><br />        Method method </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> ownerClass.getMethod(methodName, argsClass);<br /><br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> method.invoke(</span><span style="COLOR: rgb(0,0,255)">null</span><span style="COLOR: rgb(0,0,0)">, args);<br />    }<br /><br /><br /><br />    </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 新建实例<br />     *<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> className<br />     *            类名<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> args<br />     *            构造函数的参数<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 新建的实例<br />     * </span><span style="COLOR: rgb(128,128,128)">@throws</span><span style="COLOR: rgb(0,128,0)"> Exception<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object newInstance(String className, Object[] args) </span><span style="COLOR: rgb(0,0,255)">throws</span><span style="COLOR: rgb(0,0,0)"> Exception {<br />        Class newoneClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> Class.forName(className);<br /><br />        Class[] argsClass </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">new</span><span style="COLOR: rgb(0,0,0)"> Class[args.length];<br /><br />        </span><span style="COLOR: rgb(0,0,255)">for</span><span style="COLOR: rgb(0,0,0)"> (</span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> i </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,0)">0</span><span style="COLOR: rgb(0,0,0)">, j </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args.length; i </span><span style="COLOR: rgb(0,0,0)">&lt;</span><span style="COLOR: rgb(0,0,0)"> j; i</span><span style="COLOR: rgb(0,0,0)">++</span><span style="COLOR: rgb(0,0,0)">) {<br />            argsClass[i] </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> args[i].getClass();<br />        }<br /><br />        Constructor cons </span><span style="COLOR: rgb(0,0,0)">=</span><span style="COLOR: rgb(0,0,0)"> newoneClass.getConstructor(argsClass);<br /><br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> cons.newInstance(args);<br /><br />    }<br /><br /><br />    <br />    </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 是不是某个类的实例<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> obj 实例<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> cls 类<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 如果 obj 是此类的实例，则返回 true<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> </span><span style="COLOR: rgb(0,0,255)">boolean</span><span style="COLOR: rgb(0,0,0)"> isInstance(Object obj, Class cls) {<br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> cls.isInstance(obj);<br />    }<br />    <br />    </span><span style="COLOR: rgb(0,128,0)">/**</span><span style="COLOR: rgb(0,128,0)"><br />     * 得到数组中的某个元素<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> array 数组<br />     * </span><span style="COLOR: rgb(128,128,128)">@param</span><span style="COLOR: rgb(0,128,0)"> index 索引<br />     * </span><span style="COLOR: rgb(128,128,128)">@return</span><span style="COLOR: rgb(0,128,0)"> 返回指定数组对象中索引组件的值<br />     </span><span style="COLOR: rgb(0,128,0)">*/</span><span style="COLOR: rgb(0,0,0)"><br />    </span><span style="COLOR: rgb(0,0,255)">public</span><span style="COLOR: rgb(0,0,0)"> Object getByArray(Object array, </span><span style="COLOR: rgb(0,0,255)">int</span><span style="COLOR: rgb(0,0,0)"> index) {<br />        </span><span style="COLOR: rgb(0,0,255)">return</span><span style="COLOR: rgb(0,0,0)"> Array.get(array,index);<br />    }<br />}</span></div><br /></div>
		<style><![CDATA[D {
	FONT-SIZE: 12px
}
.commentTextBox {
	FONT-SIZE: 13px; FONT-FAMILY: Verdana
}
]]&gt;</style>
		<!--Beging Temp Save-->
		<style><![CDATA[userData {
	BEHAVIOR: url(#default#userdata)
}
]]&gt;</style>
		<div class="userData" id="CommentsPersistDiv">
		</div>
		<script><![CDATA[
			function TempSave(ElementID)
			{
				
				CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value);
				CommentsPersistDiv.save("CommentXMLStore");
				
			}
			function Restore(ElementID)
			{
				CommentsPersistDiv.load("CommentXMLStore");
				document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent");
			}		
]]&gt;</script>
		<!--Ene TempSave-->
		<div class="commentform">
				<a name="Feedback">
				</a>
				<table cellspacing="1" cellpadding="1" border="0">
						<tbody>
								<tr>
										<td width="75">
										</td>
										<td>
										</td>
										<td>
										</td>
								</tr>
								<tr>
										<td width="55">标题</td>
								</tr>
						</tbody>
				</table>
		</div>
<img src ="http://www.blogjava.net/19851985lili/aggbug/97638.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-02-02 20:28 <a href="http://www.blogjava.net/19851985lili/articles/97638.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java的类(class)、包(package)和接口(interface)</title><link>http://www.blogjava.net/19851985lili/articles/97637.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Fri, 02 Feb 2007 12:26:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/97637.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/97637.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/97637.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/97637.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/97637.html</trackback:ping><description><![CDATA[在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中，类(class)是用来代表对象的基本单元。对象(object)可以是现实世界中的任何一个实体，它具有若干区别于其它对象的属性和操作。而类则通过为对象定义属性和操作来概括一类实体。它封装了一组变量和方法，是生成实例对象时的模板。如一辆汽车可视为一个对象，它既具有型号、颜色、载重等特点，又有完成启动、行驶、刹车等功能。定义汽车类时需要将这些属性都包括进去，通常用数据变量代表型号、颜色、载重等属性特点，用成员方法来实现启动、行驶、刹车等操作功能。可以说类是对象的抽象，对象是类的实例化。<br />　　接口(interface)可看成一个空的抽象的类，只声明了一组类的若干同名变量和方法，而不考虑方法的具体实现。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的包(package)中包含一系列相关的类，同一个包中的类可直接互相使用，对包外的类则有一定的使用限制。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的包近似于其它语言的函数库，可提供重用的方便。<br />　　在下面各部分的详细介绍中，我们将先给出基本概念，然后结合具体实例阐明<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的类、接口、包以及封装、继承、重载等有关内容。 
<p></p><p align="left"></p><p align="center">4.1 <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的类</p><p>　　<b>4.1.1 类的声明</b></p><p>　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>是一种很典型的面向对象的程序设计语言。在面向对象的语言中，世界被看成独立的对象集合，相互间通过消息来通信。因而这种语言以数据对象为中心，而不以处理对象的代码为中心。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中的类将数据和有关的操作封装在一起，描述一组具有相同类型的对象，作为构筑程序的基本单位。<br />　　类声明定义的格式为：<br />　　[类修饰符] <a name="baidusnap1"></a><b style="COLOR: black; BACKGROUND-COLOR: #a0ffff">class类</b>名 [extends　父类名][implements　接口名] <br />其中类修饰符用于指明类的性质，可缺省。接下来的关键字class指示定义的类的名称，类名最好是唯一的。“extends 父类名”通过指出所定义的类的父类名称来表明类间的继承关系，当缺省时意味着所定义类为Object类的子类。“implements 接口名”用来指出定义的类实现的接口名称。一个类可以同时实现多个接口。类体则包括一系列数据变量和成员方法的定义声明。下面是一些略去类体的类定义例子：<br />　　public class WelcomeApp <br />　　public class Welcome extends <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.applet.Applet<br />　　public Car extends Automobile implements Runable <br />其中前两个类是我们在上一章的示例中定义的。第三个类是小汽车类Car，它的父类是交通工具类Automobile，它还实现了接口Runnable。<br />　　类修饰符是用以指明类的性质的关键字。基本的类修饰符有三个：<br />　　public，abstract和final<br />　　■public<br />　　如果一个类被声明为public，那么与它不在同一个包中的类也可以通过引用它所在的包来使用这个类；否则这个类就只能被同一个包中的类使用。<br />　　■abstract<br />　　如果一个类被声明为abstract，那么它是一个抽象的类，不能被实例化生成自己的对象，通常只是定义了它的子类共有的一些变量和方法供继承使用。被声明为abstract的抽象类往往包含有被声明为abstract的抽象方法，这些方法由它的非抽象子类完成实现细节。<br />　　■final<br />　　如果一个类被声明为final，意味着它不能再派生出新的子类，不能作为父类被继承。因此一个类不能既被声明为abstract的，又被声明为final的。<br />　　继承是面向对象程序设计中一个强有力的工具，它允许在已存在的类的基础上创建新的类。新创建的类称为其基础类的子类，基础类称为其子类的父类。子类的对象除了具有新定义的属性和方法外，还自动具有其父类定义的部分或全部属性方法。这样程序员可以在子类中重用父类中已定义好的变量和方法，只需对子类中不同于父类或新添加的部分重新定义，这样就节省了大量的时间、空间和精力。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>在类声明中使用<br />　　extends 父类名<br />的方式定义继承关系。如果不明显地写出继承的父类名，则缺省地认为所声明的类是<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的Object类的一个子类。Object类是<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中所有的类的祖先类。我们可以把这种类继承关系想象为一棵倒置的类家族树，Object类就是这棵树的根。</p><p>　　<b>4.1.2 类的组成</b></p><p>　　我们已经知道类是代表对象的，而每一个对象总有特定的状态和行为，在类中分别用变量数据和在数据上可进行的操作表示这些状态和行为。因此类的组成成分是变量和方法。变量和方法的声明格式如下：<br />　　[变量修饰符]　数据类型　变量名[=初值]　;<br />　　[方法修饰符]　返回值类型　方法名(参数表)<br />其中修饰符用来指明变量和方法的特性。变量可一次定义一个或多个，定义时可以给出初值。例如：<br />　　public int a,b=12;<br />　　protected String s="Hot <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>";<br />定义方法时一定要给出返回值类型和参数表。当没有返回值时，返回值类型记为void。参数表的形式为：<br />　　参数类型 参数值{，参数类型 参数值}<br />各参数间以逗号分隔。下面是一些简单的例子：<br />　　public static void main(String args[])<br />　　public void paint(Graphics g)<br />　　public int area(int length,int width){return length * width;}<br />其中前两个是我们在第三章已经见过的方法声明，这里略去了具体语句组成的方法体。第三个则是一个计算长方形面积的简单方法，接受整数类型的长度和宽度参数并返回它们的乘积作为结果。<br />　　变量和方法修饰符是用来指明特性的关键字，主要有以下几种：<br />　　■public<br />　　一个类中被声明为public的变量和方法是“公开”的，意味着只要能使用这个类，就可以直接存取这个变量的数据，或直接使用这个方法。<br />　　■protected<br />　　一个类中被声明为protected的变量和方法是“受限”的，意味着它们仅能被与该类处于同一个包的类及该类的子类所直接存取和使用。<br />　　■private<br />　　被声明为private的变量和方法是“私有”的，除了声明它们的类外，不能被任何其它的类直接存取和使用。<br />　　当变量或方法前不加以上三种修饰符时，被认为取friendly状态，即它们只能被同一个包中的类直接存取和使用。但不存在friendly关键字。<br />　　■static<br />　　被声明为static的变量和方法是属于类而不是属于对象的。不管这个类产生了多少个对象，它们都共享这个类变量或类方法。我们可以在不创建类实例对象时直接使用类变量和类方法。一般来说，在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中，引用一个特定的变量或方法的形式是：<br />　　对象名.变量名<br />　　对象名.方法名<br />例如：<br />　　int a=rectangle.length;<br />　　g.drawString("Welcome to <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b> World!");<br />即变量和方法是受限于对象的，但声明为static的变量或方法受限于类，使用形式是<br />　　类名.变量名<br />　　类名.方法名<br />例如：<br />　　System.out.println("Welcome to <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b> World!");<br />　　String s=String.valueOf(123);<br />这里我们并没有创建System类或String类的对象，而直接调用System类的类变量out和String类的类方法valueOf。其中valueOf方法将整形参数转换为String类对象。被声明为static的类方法在使用时有两点要特别注意：<br />　　(1)类方法的方法体中只能使用类中其它同样是static的变量或方法；<br />　　(2)类方法不能被子类修改或重新定义。<br />　　■final<br />　　将变量或方法声明为final，可以保证它们在使用中不被改变。被声明为final的变量必须在声明时给定初值，而在以后的引用中只能读取，不可修改。被声明为final的方法也同样只能使用，不能重载。<br />　　■abstract<br />　　这个修饰符仅适用于方法。被声明为abstract的方法不需要实际的方法体，只要提供方法原型接口，即给出方法的名称、返回值类型和参数表，格式如下：<br />　　abstract　返回值类型　方法名(参数表)；<br />定义了abstract抽象方法的类必须被声明为abstract的抽象类。</p><p>　　<b>4.1.3 构造方法和finalizer</b></p><p>　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中有两个特殊的方法：用于创建对象的构造方法(constructor)和用于撤销对象的方法finalizer，相当于C++中的构造函数和析构函数。构造方法是生成对象时编译器自动调用的方法，用以给出对象中变量的初值。构造方法必须与类同名，而且绝对不允许有返回值，甚至不允许以void来标记无返回值。一个类的构造方法可以有多个，以不同的参数表区分不同的情形，这是<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>多态性的一个体现。下面是一个简单的例子。<br />　　例4.1 Rectangle类的构造方法。<br />　　class Rectangle{<br />　　　protected int width;/*类Rectangle的两个整型变量*/<br />　　　protected int height;/*分代表长方形的长和宽*/<br />　　　/*下面是类Rectangle的三个构造方法*/<br />　　　/*第一个构造方法，无参数，缺省地给出长和宽*/<br />　　　　Rectangle()<br />　　　/*第二个构造方法，给出长、宽参数*/<br />　　　　Rectangle(int w,int h)<br />　　　/*第三个构造方法，给出另一个Rectangle作参数*/<br />　　　　Rectangle(Rectangle r)<br />　　　　{width=r.width();<br />　　　　　height=r.height();<br />　　　　}<br />　　　/*下面是类Rectangle的另外两个方法，分别为取长和宽的值*/<br />　　　　public int width()<br />　　　　　{return width;}<br />　　　　public int height()<br />　　　　　{return height;}<br />　　}<br />　　class Test{<br />　　　Rectangle r1=new Rectangle();/*调用第一个构造方法*/<br />　　　Rectangle r2=new Rectangle(12,20);/*调用第二个构造方法*/<br />　　　Rectangle r3=new Rectangle(r1);/*调用第三个构造方法*/<br />　　}<br />　　在这个例子中Rectangle有三个构造方法，它们的名字相同，参数不同因而采用的调用形式也不同。第一个构造方法不需要任何参数，调用时系统自动地给出统一的固定的长方形的宽和高(这里我们设定为20和30)。第二个构造方法需要两个整形参数，根据用户给出的长方形的宽和高创建长方形对象。第三个构造方法需要一个长方形参数，创建出与这个长方形具有同样的宽和高的长方形对象。在Rectangle类中，width和height都是protected的，不宜直接存取。为了使用方便，我们定义出width()和height()方法来获得一个特定长方形的宽和高，再将取得的数值传递给新创建的对象。像这样在一类中有两个或两个以上同名方法的现象叫Overloading，是多态的一种表现。这样同名方法应该有且必须有不同的参数表，调用时编译系统就是根据参数的匹配情况，包括个数和类型，来决定实际使用哪一个方法的。如果两同名方法的参数表也相同，会造成混淆，编译时将得到出错信息：<br />　　Duplicate method declaration<br />　　(重复的方法声明)<br />　　为了实际创建出对象，我们要使用new。系统执行遇到new，才根据new后面跟随的构造方法名和参数表，选择合适的构造方式，分配内存，创建对象并初始化。一个类若没有显示地定义构造方法，使用new时将调用它的父类的构造方法，这种上溯可一直到达Object类，而Object类的构造方法是语言预先定义好的。<br />　　相对于构造方法，在对象被撤销时调用的方法是finalizer。对所有的类，它的原始定义形式都是一样的：<br />　　void finalize();<br />没有返回值，而且没有任何参数。一般来说，由于<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的内存管理是由系统自动完成，通常不需要我们重写这个方法，而让它自然而然地从父类(最终也就是从Object类)继承。只有当某些资源需要自动归还时，才需要将这一方法重写。</p><p>　　<b>4.1.4 重写(Overriding)和重载(Overloading)</b></p><p>　　方法的重写Overriding和重载Overloading是<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>多态性的不同表现。前者是父类与子类之间多态性的一种表现，后者是一个类中多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数，我们说该方法被重写(Overriding)。子类的对象使用这个方法时，将调用子类中的定义，对它而言，父类中的定义如同被“屏蔽”了。如果在一个类中定义了多个同名的方法，它们或有不同的参数个数或有不同的参数类型，则称为方法的重载(Overloading)。这在例4.1中已经可以看到。下面再给出两个简单的例子，分别显示Overriding和Overloading。<br />　　例4.2 Overriding的例示<br />　　class Father{<br />　　　void speak(){<br />　　　　System.out.println("I am Father!");//父类定义的speak方法<br />　　　}<br />　　}<br />　　class Son extends Father{<br />　　　void speak(){<br />　　　　System.out.println("I am Son!");//子类重写的speak方法<br />　　　}<br />　　}<br />　　public class Check{<br />　　　public static void main(String args[]){<br />　　　　Son x=new Son();<br />　　　　x.speak();//调用子类的speak方法<br />　　　}<br />　　}<br />　　//output of class Check!<br />　　I am Son!<br />　　从这个例子我们可以看到，类Son中的speak()方法重写了其父类Father中一模一样的方法，而它的对象x调用speak()方法的结果是与Son中定义致的。<br />　　例4.3　Overloading例示。<br />　　class Father{<br />　　　void speak(){　　//无参的speak方法<br />　　　　System.out.println("I am Father.");<br />　　　}<br />　　　void speak (String s){　　//有参的speak方法<br />　　　　System.out.println("I like"+s+".");<br />　　　}<br />　　}<br />　　public class Check{<br />　　　public static void main(String args[]){<br />　　　　Father x=new Father();<br />　　　　x.speak();//调用无参的speak方法<br />　　　　x.speak("music");//调用有参的speak方法<br />　　　}<br />　　}<br />　　//out put of class Check<br />　　I am Father<br />　　I like music.<br />　　这个例子中类的Father定义了两个speak方法，在类Check中又两次调用，一次无参，一次有参，打印出两行不同的字符串。注意<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>在打印字符串时，字符串间的连接用符号“+”来完成。</p><p>　　Overriding是父类与子类之间多态性的一种表现；Overloading是一个类中多态性的一种表现。</p><p>　　<b>4.1.5 几个特殊的变量：null，this和super</b></p><p>　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中有三个特殊的变量：null,this和super，这三个变量是所有的类都可以使用的，用来指示一些特定的对象。<br />　　null相当于“空”，可以用来代指任何对象，但没有实例。如<br />　　　　Rectangle r=null;<br />创建了一个Rectangle的变量r，但并没有一个Rectangle的实例对象由r来代表。r就如同一个可放置Rectangle的盒子，只是这个盒子现在是空的。<br />　　this用以指代一个对象自身。它的作用主要是将自己这个对象作为参数，传送给别的对象中的方法。它的使用形式是这样的：<br />　　class Painter{<br />　　　　...<br />　　　　void drawing(Father y){<br />　　　　...<br />　　　　}<br />　　}<br />　　class Father{<br />　　　　...<br />　　　　void draw(Painter x)<br />　　　　{...<br />　　　　　x.drawing(this);/*将自身传递给x的drawing方法*/<br />　　　　　　...<br />　　　　}<br />　　}<br />　　class Test{<br />　　　...<br />　　　Father f=new Father();<br />　　　Painter p=new Painter();<br />　　　f.draw(p);<br />　　　...<br />　　}<br />例中调用Father类的draw方法时，使用语句<br />　　f.draw(p);<br />又Father类中定义draw方法时以this为参数调用了类Painter的drawing方法：<br />　　x.drawing(this);<br />因而实际上调用了Painter类对象p的drawing方法，而将Father类对象f作为参数传递给drawing方法.<br />　　super用来取用父类中的方法和变量数据。它的用法如在下面的例子中所示。<br />　　例4.4在类中使用super的例示。<br />　　/* Check.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b> */<br />　　class Father{<br />　　　void speak(){<br />　　　　System.out.println("I am Father.");<br />　　　}<br />　　　void speak(String s){<br />　　　　System.out.println("I like "+s+".");<br />　　　}<br />　　}<br />　　class Son extends Father{<br />　　　void speak(){<br />　　　　System.out.println("My father says.");<br />　　　　super.speak();//相当于调用Father类的speak()方法<br />　　　　super.speak("hunting");<br />　　　　　//相当于调用Father类的speak(String s)方法<br />　　　}<br />　　}<br />　　class Check{<br />　　　public static void main(String args[]){<br />　　　　Son s=new Son();<br />　　　　s.speak();<br />　　　}<br />　　}<br />　　//Check.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>的执行结果：<br />　　My father says:<br />　　I am Fater.<br />　　I like hunting.<br />　　在这个例子中，类Son的speak()方法语句<br />　　super.speak();<br />　　super.speak("hunting");<br />实际调用了Son的父类Father中的speak()和speak(String s)方法，以实现执行结果后两行的输出。使用父类的变量形式也很类似。<br />　　super.变量名<br />　　super和this的另一个重要用途是用在构造方法中。当一个类中不止一个构造方法时，可以用this在一个构造方法中调用中一个构造方法。若想调用父类的构造函数，则直接使用super。例如我们可心如下定义例4.1中类Rectangle的子类ColorRectangle:<br />　　public class ColorRectaqngle extends Rectangle{<br />　　　int color;<br />　　　ColorRectangle(int w,int h,int c){<br />　　　　super(w,h);<br />　　　　color=c;<br />　　　}<br />　　　...<br />　　}<br />　　与父类Rectangle相比，类ColorRectangle增加了color成员变量代表长方形的颜色。在它的构造方法中，用语句<br />　　　　super(w,h);<br />调用了类Rectangle的构造方法<br />　　　　Rectangle(int w,int h);<br />设定长方形的长和宽，然后就只需设定长方形的颜色：<br />　　　　color=c;<br />这样大大提高了代码的重用性。<br /></p><p align="center">4.2 <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的包</p><p>　　在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中，包的概念和目的都与其它语言的函数库非常类似，所不同的只是其中封装的是一组类。为了开发和重用的方便，我们可以将写好的程序类整理成一个个程序包。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>自身提供了21个预先设定好的包，下面列出其中主要的几个，其余读者参看<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的API：<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.lang　　　　提供基本数据类型及操作<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.util　　　　提供高级数据类型及操作<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.io　　　　　提供输入/输出流控制<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.awt　　　　　提供图形窗口界面控制<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.awt.event　　提供窗口事件处理<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.net　　　　　提供支持Internet协议的功能<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.applet　　　提供实现浏览器环境中Applet的有关类和方法<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.sql　　　　　提供与数据库连接的接口<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.rmi　　　　　提供远程连接与载入的支持<br />　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.security　　提供安全性方面的有关支持<br />　　我们可以引用这些包，也可以创建自己的包。</p><p>　　<b>4.2.1 包的声明</b></p><p>　　为了声明一个包，首先必须建立一个相应的目录结构，子目录名与包名一致。然后在需要放入该包的类文件开头声明包，形式为：<br />　　package 包名；<br />这样这个类文件中定义的所有类都被装入到你所希望的包中。例如<br />　　package Family;<br />　　class Father{<br />　　　...//类Father装入包Family<br />　　}<br />　　class Son{<br />　　　...//类Son装入包Family<br />　　}<br />　　class Daughter{<br />　　　...　　//类Daughter装入包Family<br />　　}<br />不同的程序文件内的类也可以同属于一个包，只要在这些程序文件前都加上同一个包的说明即可。譬如：<br />　　//文件 Cat.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />　　package Animals;<br />　　class Cat{/*将类Cat放入包Animals中*;<br />　　...<br />　　}<br />　　//文件Dog.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />　　package Animals;<br />　　class Dog{　　/*将类Dog放入包Animals中*/<br />　　...<br />　　}</p><p>　　<b>4.2.2 包的使用</b></p><p>　　在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中，为了装载使用已编译好的包，通常可使用以下三种方法：<br />　　(1) 在要引用的类名前带上包名作为修饰符。如：<br />　　Animals.Cat cat=new Animals.Cat();<br />其中Animals是包名，Cat是包中的类，cat是类的对象。<br />　　(2)在文件开头使用import引用包中的类。如：<br />　　import Animals.Cat;<br />　　class Check{<br />　　　Cat cat=new Cat();<br />　　}<br />同样Animals是包名，Cat是包中的类，cat是创建的Cat类对象。<br />　　(3)在文件前使用import引用整个包。如：<br />　　import Animals.*;<br />　　class Check{<br />　　　Cat cat=new Cat();<br />　　　Dog dog=new Dog();<br />　　　...<br />　　}<br />Animals整个包被引入，Cat和Dog为包中的类，cat和dog为对应类的对象。<br />　　在使用包时，可以用点“.” 表示出包所在的层次结构，如我们经常使用的<br />　　import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.io.*;<br />　　import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.applet.*;<br />实际是引入了/<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>/io/或/<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>/applet/这样的目录结构下的所有内容。需要指出的是，<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.lang这个包无需显式地引用，它总是被编译器自动调入的。使用包时还要特别注意系统classpath路径的设置情况，它需要将包名对应目录的父目录包含在classpath路径中，否则编译时会出错，提示用户编译器找不到指定的类。</p><p align="center">4.3 一个邮件类(Mails)的例子</p><p>　　下面我们给出一个较大的例子，让读者在实例中进一步熟悉<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的类和包。<br />　　这里所有的类都放在包ch4package中，先定义出一个虚基类Mails，然后派生出它的两个子类Parcel(包裹)和Remittance(汇款)。Show类用于实际执行，允许用户创建自己的邮件，然后显示出所有的邮件信息。为了方便地存取邮件，还定义了类ShowMails。接下来我们逐一介绍这经些类。<br />　　例4.5 类Mails程序文件。<br />　　1：package ch4package;<br />　　2: public abstract class Mails{<br />　　3: 　protected String fromAddress;<br />　　4: 　protected String toAddress;<br />　　5: 　public abstract void showMe();<br />　　6: }<br />　　类Mails是一个虚类，不能产生自己的实例对象，而只是描述了邮件最基本的特性。类文件的开头首先用<br />　　　　package cha4package;<br />表明Mails类是放于ch4package这个包里的。然后程序第二行为Mails的类声明。<br />　　　　public abstract class Mails<br />　　用修饰符abstract指出这是个虚类。第三至第四行Mails类中定义了两个变量：<br />　　　　protected String fromAddress;<br />　　　　protected String toAddress;<br />fromAddress和toAddress ,分别代表邮件的寄出地址和送往地址，都是protected类型的，这样cha4package包外的类不能直接引用，保证了信息的隐藏。第五行Mails类定义了方法<br />showMe()，用于显示一个邮件自身的有在信息：<br />　　　　public abstract voi showMe();<br />声明时以abstract修饰，意味着这是一个抽象方法，只给出原型，具体实现要由Mails类的非虚子类通过Overriding完成。<br />　　接下来是Mails的两个非虚子类。<br />　　例4.6　类Parcel和类Remittance程序文件。<br />　　//Parcel.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />　　1: package ch4package;<br />　　2: 　public class Parcel extends Mails{//邮件类的子类Parcel类<br />　　3: 　　protected int weight;<br />　　4: 　　Parcel(String address1,String address2,int w){//构造方法<br />　　5: 　　fromAddress=address1;<br />　　6: 　　toAddress=address2;<br />　　7: 　　weight=w;<br />　　8: 　}<br />　　9: 　public void showMe(){<br />　　10:　　System.out.print("Parcel:");<br />　　11:　　System.out.println("\tFrom:"+fromAddress+"\tTo:"+toAddress);<br />　　12:　　System.out.println("\tWeigth:"+weight+"g");}<br />　　13:　}<br />　　//Remittance.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />　　1: package ch4package;<br />　　2: 　public class Remittance extends Mails{//邮件类的子类Remittance<br />　　3: 　　protected int money;<br />　　4: 　　Remittance(String address1,String address2,int m){//构造方法<br />　　5: 　　fromAddress=address1;<br />　　6: 　　toAddress=address2;<br />　　7: 　　money=m;<br />　　8: 　}<br />　　9: 　public void showMe(){//显示邮件信息<br />　　10:　　System.out.println("Remittance:");<br />　　11:　　System.out.println("\tFrom:"+fromAddress+"\tTo:"+toAddress);<br />　　12:　　System.out.println("\tMoney:"+money+" Yuan");<br />　　13:　}<br />　　14:}</p><p>这里是邮件的两个子类：包裹Parcel和汇款Remittance。以类Parcel为例详细说明。首先在程序开头写出：<br />　　package ch4package;<br />　　一方面将类Parcel装入包ch4package，另一方面方便类Parcel使用包ch4package中的其它类，如已定义的Mails类。接下来类Parcel声明时用<br />　　extends Mails<br />表明自己是Mails的一个子类。在第三行Parcel声明了一个weight变量，用来代表包裹的重量。加上从父类Mails继承下来的变量fromAddress和toAddress，类Parcel一共有三个成员变量：<br />　　寄出地址　fromAddress，寄达地址toAddress和重量weight<br />　　相对应的，它的构造方法Parcel也必须有三个参数，分别传递给三个成员变量。构造方法的定义如第四行至第八行所示。由于Parcel类不是虚类，所以必须在其中重写完成它的父类Mails中声明的抽象方法showMe。Parcel的showMe()方法仅仅是将自己的邮件类型和三个变量的信息在屏幕上显示出来。<br />　　类Remittance与Parcel非常相似，只是它定义的变量为money，用来代表汇款的金额。它也必须具体完成方法showMe。<br />　　下面我们看到的是用于存取邮件的类ShowMails。<br />　　例4.7 类ShowMails程序文件。<br />　　1: package ch4package;<br />　　2: import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.lang.*;<br />　　3: public class ShowMails{<br />　　4: 　protected Mails showList[];//邮件数组序列<br />　　5: 　protected static final int maxMails=50;//最大邮件个数<br />　　6: 　protected int numMails;//当前邮件个数<br />　　7: 　ShowMails(){<br />　　8: 　　showList=new Mails[maxMails];<br />　　9: 　　numMails=0;<br />　　10:　}<br />　　11:　public void putMails(Mails mail){<br />　　12:　　if(numMails&lt;maxMails){<br />　　13:　　　showList[numMails]=mail;//加入邮件<br />　　14:　　　numMails++;//修改计数<br />　　15:　　}<br />　　16:　}<br />　　17:　public Mails getMails(int index){//获取邮件<br />　　18:　　if((0&lt;=index)&amp;&amp;(index&lt;numMails)) return showList[index];<br />　　19:　　else return null;<br />　　20:　}<br />　　21:　public void showAll(){//展示邮件<br />　　22:　　if(numMails&gt;0)<br />　　23:　　　for (int i=0;i&lt;numMails;i++){<br />　　24:　　　　System.out.print("Mail NO"+(i+1)+":");//邮件序号<br />　　25:　　　　showList[i].showMe();//邮件具体信息<br />　　26:　　　}<br />　　27:　　else<br />　　28:　　　System.out.println("No mails.");<br />　　29:　}<br />　　30:　public int mailnum(){<br />　　31:　　return numMails;<br />　　32:　}<br />　　33:}<br />　　程序第四行至第六行类ShowMails定义了三个成员变量：<br />　　　　showList[],maxMails和numMails<br />　　变量showList[]是类Mails的一个数组。但由于Mails本身是个虚类，因而showList[]的元素不可能是Mails的对象，它实际上是用来存放Mails的两个子类Parcel和Remittance的对象的。一般说来，一个被声明为类A的的变量，总可以被赋值为任何类A的子类的实例对象。这与父子类之间的类型转换的原则是一致的：父类到子类的转换可以隐式地自动进行，而子类到父类的转换则需要显式地加以说明。<br />　　变量maxMails用来指出showList[]中最多可容 纳的邮件数，它对ShowMails的所有对象都应是固定且一致的。因此它被声明为tatatic和final的，为所有对象共享且不可更改。变量numMails则用来作为showList[]中实际邮件个数的计数。<br />　　对应ShowMails的三个成员变量，我们在ShowMails()构造方法中只需做两件事：实际创建类mails的数组showList[]，然后将邮件计数numMails置零。<br />　　第11行开始的方法putMails和第17行开始的方法getMails分别完成对showList[]中邮件的存取。第30行的mailnum方法则返回当时的邮件计数值。putMails方法接受一个邮件类参数，并把它加入到当前邮件序列的末尾。getMails方法接受一个整型参数作为邮件序号，根据该序号找出当前邮件序列中对应邮件返回。当给定的邮件号index不在有效范围时，以据该序号找出当前邮件序列中对应邮件返回。当给定的邮件号index不在有效范围时，以<br />　　　　return null;(19行)<br />返回一个定值。这一句看上去并没有完成什么实质性的工作，但如果省略则编译时会出错。因为getMails方法的返回值已声明为Mails类，这就要求在任何情况下都返回一个符合这一要求的值。而空变量null可与任何类型匹配，恰好能适合这样的要求。<br />　　第21行的方法showAll显示showList[]中所有邮件的信息。每一邮件首先显示自己的邮件号。因为showList[]数组的下标从0开始，为了符合人们的日常习惯，将每一个下标加1后再作为邮件号输出。各个邮件的显示是调用邮件的showMe()方法来实现的。因为showMe()方法已经在虚类Mails中定义了，所以不管showList[]中的实际元素是Parcel还是Remittance，编译器总能顺利地连接调用相应的代码。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>面向对象特性中的动态绑定(Dynamic Binding)，保证了无需在编译前确定地知道showList[]每一个数组元素的类型，就能成功地实现这样的链接。<br />　　最后给出的类是实际执行的Shos类。<br />　　例4.8 类Show程序文件<br />　　1: package ch4package;<br />　　2: import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.io.*;<br />　　3:<br />　　4: public class Show{<br />　　5:　public static ShowMails board=new ShowMails();//邮件库变量<br />　　6:　　public static void main(String args[])throws IOException{<br />　　7: 　　　boolean finished=false;<br />　　8:　　　BufferedReader in =new BufferedReader(new InputStreamReader(System.in));<br />　　9:　　　while(!finished){//添加邮件<br />　　10:　　　　System.out.print("\nDo you want to add mails(Y/N)?");<br />　　11:　　　　System.out.flush();<br />　　12:　　　　char ch=in.readLine().charAt(0);<br />　　13:　　　　if('Y'==Character.toUpperCase(ch)){//输入地址<br />　　14:　　　　System.out.println("Address information:");<br />　　15:　　　　System.out.print("\tFrom:");<br />　　16:　　　　System.out.flush();<br />　　17:　　　　String address1=in.readLine();<br />　　18:　　　　System.out.print("\tTo:");<br />　　19:　　　　System.out.flush();<br />　　20:　　　　String address2=in.readLine();<br />　　　　　　//选择邮件各类(包裹或汇款)<br />　　21:　　　　System.out.print("Choose the mail type:1-Parcel 2-Remittance ");<br />　　22:　　　　System.out.flush();<br />　　23:　　　　ch=in.readLine().charAt(0);<br />　　24:　　　　if('1'==ch){//输入包裹重量<br />　　25:　　　　　System.out.print("Parce\tWeight:");<br />　　26:　　　　　System.out.flush();<br />　　27:　　　　　int w=getInt();<br />　　28:　　　　　Parcel pa=new Parcel(address1,address2,w);<br />　　29:　　　　　board.putMails(pa);<br />　　30:　　　　}<br />　　31:　　　　if('2'==ch){//输入汇款金额<br />　　32:　　　　　System.out.print("Remittance\tMoney:");<br />　　33:　　　　　System.out.flush();<br />　　34:　　　　　int m=getInt();<br />　　35:　　　　　Remittance re=<br />　　　　　　　　　　new Remittance(address1,address2,m);<br />　　36:　　　　　board.putMails(re);<br />　　37:　　　　}<br />　　38:　　　}<br />　　39:　　　else finished=true;<br />　　40:　　}<br />　　41:　　System.out.println(" ");<br />　　42:　　board.showAll();//输出所有邮件信息<br />　　43:　}<br />　　　//键盘输入获取整数<br />　　44:　public static int getInt() throws IOException{<br />　　45:　　BufferedReader in= new BufferedReader<br />　　　　　　　(new InputStreamReader(System.in));<br />　　46:　　String st=in.readLine();<br />　　47:　　Integer i=new Integer(st);<br />　　48:　　return i.intValue();<br />　　49:　}<br />　　50:}<br />　　由于涉及交互，类Show中用到了许多输入输出语句，我们在程序第2行用<br />　　　　import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.io.*;<br />引入<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的IO包。这个包封装了大量有关输入输出的方法，具体内容将在第七章中详细介绍。这里我们只需要弄清楚所用到的输入/出语句的功能。<br />　　在输入/出中，总有可能产生输入输出错误，<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>反这引起错误都归入IOException(IO异常)因为我们不打算在程序中加入对这些异常的处理，所以需要在每个方法的参数表后用关键字throws“扔出”这些异常，如第6行<br />　　　　public static void main(String args[])throws IOException<br />这样异常发生时，将自动中止程序运行并进行标准处理。请参看第五章的内容。<br />　　程序的输入来源是一个BufferedReader类的对象in，它的声明在第８行：<br />　　BufferedReader in=new BufferedReader(new InputStreamReader(System.in));<br />因而具有BufferedReader中定义的所有输入功能。<br />　　in.readLine()<br />是读入一行输入，并返回一字符串。而<br />　　charAt(i)<br />是String类的一个方法，取得指定字符串的第i个元素作为字符型返回。这两上方法边用，则可取得想要的输入。而在输入前用<br />　　System.out.flush();<br />将缓冲清空，以保证输入的正确性。<br />　　System.out.print<br />　　System.out.println<br />都是输出语句，不同的只是后者在输出结束后自动换行。类System和getInt()中用到的类都是Interger(注意不是int!)都在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的lang名中定义，我们将在第六章详细介绍。<br />　　在了解以上的基本输入输出后，这个程序就变得较等了。为了方便起见，我们不失一般性的将Show类的所有成员都定义为static的，这样，类Show就不同志需要特别定义的构造方法了。在第５行声明的变量board是ShowMails类的对象，用来建立邮件库：<br />　　public static ShowMails board=new ShowMails();<br />第44行开始的getInt方法用来从键盘输入获得一个整数。第6行开始的main方法则是程序的主体。它实现的功能是不断询问是否要加入新邮件，肯定回答时要求选择邮件类型并输入相应信息。据此创建邮件子类对象并加入board中，直至得到不定回答退出。最后显示此时已有的邮件信息。邮件的加入和显示都通过简单的<br />　　　　board.pubMails()<br />　　　　board.showAll()<br />调用ShowMails的方法来实现的，简洁明了而层次清晰。这就是面向对象进行数据封装和重用的优点所在。要执行类Show，我们需要将例4.5～例4.8的文件依次输入、编译。最后用解释器<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>执行类Show。下面给出的是Show的运行结果，其中加下划线“_”的是键盘输入。<br />　　例4.9　类Show运行结果。<br />　　D:\<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>01&gt;<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b> ch4package.Show</p><p>　　Do you want to add mails(Y/N)?n　//询问有是否添加邮件</p><p>　　No mails.　　　　　　　　　　　　　//显示没有邮件</p><p>　　D:\<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>01&gt;<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b> ch4package.Show</p><p>　　Do you want to add mails(Y/N)?y//询问有是否添加邮件<br />　　Address information:　　　　　　//要求输入地址信息<br />　　From:NanJing<br />　　To:BeiJing<br />　　Choose the mail type:1-Parcel 2-Remittance 1//要求选择邮件类型<br />　　Parce Weight:100//要求输入包裹重量</p><p>　　Do you want to add mails(Y/N)?y<br />　　Address information:<br />　　From:ShangHai<br />　　To:TianJing<br />　　Choose the mail type:1-Parcel 2-Remittance 2<br />　　Remittance Money:400//要求输入汇款金额</p><p>　　Do you want to add mails(Y/N)?n</p><p>　　Mail NO1:Parcel://输出所有邮件信息<br />　　　　 From:NanJing To:BeiJing<br />　　Weigth:2g<br />　　Mail NO2:Remittance:<br />　　From:ShangHai To:TianJing<br />　　Money:400 Yuan</p><p>　　D:\<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>01</p><p align="center">4.4 <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的接口</p><p>　　<b>4.4.1 引进接口的目的</b></p><p>　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的接口也是面向对象的一个重要机制。它的引进是为了实现多继承，同时免除C++中的多继承那样的复杂性。前面讲过，抽象类中包含一个或多个抽象方法，该抽象类的子类必须实现这些抽象方法。接口类似于抽象类，只是接口中的所有方法都是抽象的。这些方法由实现这一接口的不同类具体完成。在使用中，接口类的变量可用来代表任何实现了该接口的类的对象。这就相当于把类根据其实现的功能来分别代表，而不必顾虑它所在的类继承层次。这样可以最大限度地利用动态绑定，隐藏实现细节。接口还可以用来实现不同类之间的常量共享。<br />　　为了说明接口的作用，我们不妨假设有一系列的图形类，其中一部分在图形中加入了文字，成为可编辑的，它们应当支持最普遍的编辑功能：<br />　　cut，copy，paste和changeFont<br />将这些方法的原型统一组合在一个EditShape接口中，就可以保证方法名的规范统一和使用的方便。我们画出这个假想的类和接口的继承关系图，可以更直观地了解。</p><p>　　　　　　　　　　　　　　　　　　　　Object<br />　　　　　　　　　　　　　　　　　　　　　↓<br />　　　　　　　　　　　　　　　　　　　　Shape<br />　　　　　　　　┌────────────┼─────────────┐<br />　　　　　　　　↓　　　　　　　　　　　　↓　　　　　　　　　　　　　↓<br />　　　　　　　Circle 　　　　　　　　　Rectangle 　　　　　　　　　Triangle<br />　　　　　　　↙　↘　　　　　　　　　　↙　↘　　　　　　　　　　　　↙　↘<br />　　PaintCircle TextCircle PaintRectangle TextRectangle PaintTriangle TextTrangle<br />　　　　　　　　　　　↑　　　　　　　　　　　↑　　　　　　　　　　　　　　　↑<br />　　　　　　　　　　　└───────────┼───────────────┘<br />　　　　　　　　　　　　　　　　　　　　　　EditShape<br />　　　　　　　　图4.1　Shape 和 EditShape</p><p>　　以图中类Circle的两个子类为例。类PaintCircle未实现EditShape接口，不支持上述编辑功能。而类TextCircle既是Cricle的子类，又实现了EditShape接口，因而不但具有Circle类的图形牲，又支持EditShape定义的编辑功能。而在TextCircle，TextRectangle和TextTriangle中，支持这些编辑功能的方法是同名同参的(与EditShape的定义一致)，这又提供了使用上的方便。</p><p>　　<b>4.4.2 接口的声明和使用</b></p><p>　　<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的接口类似于抽象类，因而它的声明也和抽象类类似，只定义了类中方法的原型，而没有直接定义方法的内容。它的声明格式为：<br />　　[接口修饰符] interface　接口名 [extends 父类名]<br />　　　　<br />　　接口修饰符可以是public或abstract，其中abstract缺省时也有效。public的含义与类修饰符是一致的。要注意的是一个编译单元，即一个.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>文件中最多只能有一个public的类或接口，当存在public的类或接口时，编译单必须与这个类或接口同名。<br />　　被声明的变量总是被视为static和final的，因而必须在声明时给定初值。被声明的方法总是abstract的，abstarct缺省也有效。与抽象类一样，接口不需要构造方法。接口的继承与为是一样的，当然一个接口的父类也必须是接口。下面是一个接口的例子：<br />　　interface EditShape{<br />　　　void cut();<br />　　　void copy();<br />　　　void paste();<br />　　　void changeFont();<br />　　}<br />在使用时，为了将某个接口实现，必须使用关键字implements。格式是这样的：<br />　　[类修饰符] class 类名 [extends 父类名] [<font color="#ff0000">implements</font> 接口名表]<br />其中，接口名表可包括多个接口名称，各接口间用逗号分隔。“实现(implements)“了一个接口的非抽象类必须写出实现接口中定义的方法的具体代码，同时可以读取使用接口中定义的任何变量。<br />　　例4.10　接口的实现<br />　　class TextCircle extends Circle implements EditShape<br />　　{...<br />　　　void cut()　　　　　<br />　　　void copy()　　　　<br />　　　void paste()　　　　<br />　　　void changeFont　　　<br />　　　...<br />　　}</p><p>　　<b>4.4.3 多继承</b></p><p>　　在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中，类之间只允许单继承，但我们可以把一个类实现的接口类也看作这个类的父类。类从它实现的接口那里“继承”了变量和方法，尽管这些变量是静态常量，这些方法是未实现的原型。如果一个类实现的接口类不止一个，那么所有这些接口类都被视为它的“父类”。这样，实现了一个或多个接口的类就相当于是从两个(加上该类原有意义上的父类)或两个以上的类派生出来的。<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的多继承正是建立在这种意义之上。通过接口的继承，相当于只选择了一部分需要的特征汇集在接口中由不同的类共享并继承下去，而不必通过父子类间的继承关系将所有的方法和变量全部传递给子类。所以我们又可以把<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>的这种多继承称为“有选择的多继承”。这种多继承与一般的多继承相比，更为精简，复杂度也随之大大降低。<br />　　在多继承时，一个子类可能会从它的不同父类那里继承到同名的不同变量或方法，这往往会引起两义性问题，即不知道子类中这样的变量或方法究竟是继承了哪一个父类的版本，在<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中，为了防止出现这样的两义性问题，规定不允许一个子类继承的父类和实现的接口类中定义同名的不同变量，否则编译该子类时将出错，无法通过。而对于方法，由于接口类中定义的总是abstract的方法原型，而没有实际代码，所以不会出现类似的两义性问题。相反，常会存在这样的情况：当接口类中要求实现的方法子类没有实现，而子类的父类中定义有同名方法时，编译器将子类从父继承的该方法视为对接口的的实现。这样的继承和实现都被认为是合法的。</p><p align="center"><b>4.5 实现了接口的邮件类例子</b></p><p>　　这一节我们将4.3节邮件类的例子加以改进和扩展，加入有关接口的内容，以说明接口和多继承的概念。<br />　　首先定义一个名为MailPost的接口，其中没有定义变量，而是给出两个有关邮寄方法原型。<br />　　calPrice()计算邮费并以浮点数形式返回；<br />　　post()完成邮寄。<br />　　例4.11 接口MailPost。<br />　　//MailPost.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />　　package ch4package;<br />　　public interface MailPost{<br />　　　public float claPrice();<br />　　　public void post();<br />　　}<br />　　接下来在包裹Parcel和汇款Remittance的基础上分别派生出可邮寄的包裹和汇款：PostParcel和PostRemit两个子类。<br />　　例4.12　子类PostParcel和PostRemit。<br />　　---------------------------------<br />　　//PostParcel.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />package ch4package;<br />import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.lang.*;<br /><br />public class PostParcel extends Parcel implements MailPost{<br />protected int postage;<br />protected boolean postable;<br />protected boolean posted;<br />PostParcel(Ttring address1,String address2,int w,intp){<br />//构造方法<br />super(address1,address2,w);<br />postage=p;<br />postable=false;<br />posted=false;<br />}<br />public float calPrice(){//计算邮资<br />return((float)0.05*weight);<br />}<br />public void post(){//邮寄包裹<br />float price=calPrice();<br />postable=(price&lt;=postage);<br />posted=true;<br />}<br />public void showMe(){//显示邮件信息<br />float price=calPrice();<br />System.out.println("Postable Parcel:");<br />System.out.println("\tFrom:")+fromAddress+\tTo"<br />+toAddress);<br />System.out.println("\tWeigth:)+weigth+"g\tPostage:"<br />+postage+"Yuan");<br />if(posted){<br />if(postable)System.out.println("\tIt has been<br />posted !");<br />else{<br />System.out.println("\tIt needs more postage:");<br />System.out.println("\tThe current postage<br />is:"+postage+"Yuan");<br />System.out.println("\t\tThe price is:"+price+"Yuan");<br />}<br />}<br />}<br />}<br />//PostRemit.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br />package ch4package;<br />import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.lang.*;<br /><br />public class PostRemit exteds Remittance implements MailPost{<br />protected int postage;<br />portected boolean postable;<br />protected boolean posted;<br />PostRemit(String address1,String address2,int m,int p){<br />//构造方法<br />super(address1,address2,m);<br />postage=p;<br />postable=false;<br />posted=false;<br />}<br />public float calPrice(){//计算邮资<br />float price=cealPrice();<br />postable=(price&lt;=postage);<br />posted=true;<br />}<br />public void showMe(){//显示邮件信息<br />float price=calPrice();<br />System.out.println("Postable Remit:");<br />System.out.println("\tFrom:"+fromAddress+"\tTo:"<br />+toAddress);<br />System.out.println("\tMoney:"+money+"Yuan"+"\tPostage:"<br />+postage+"Yuan");<br />if(posted){<br />if(postable)System.out.println("\tIt has been<br />posted!");<br />else{<br />System.out.println("\tIt needs more postage:");<br />System.out.println("\t\tThe current postage is:"<br />+postage+"Yuan");<br />System.out.println("\t\tThe price is:"<br />+price+"Yuan");<br />}<br />}<br />}<br />}<br /><br />　　---------------------------------<br />　　这两个类都实现了接口MailPost。由于两个类非常相似，我们仍然重点讲解其中一个：类PostParce。<br />　　PostParcel仍是包ch4package中的一员，它是类Parcel的子类(extends Parcel)，又实现了接口MailPost(implements MailPost)：<br />　　　　public class PostParcel extends Parcel implements MailPost<br />　　在Parcel的基础上，它新增加了三个变量：<br />　　　　postage，posted，postable<br />其中整型的postage用来记录邮寄人提供的邮资，布尔型的posted和postable分别用来记录是否被尝试邮寄过以及邮寄是束成功。在PostParcel的构造方法中，第9行语句<br />　　　　super(address1,address2,w);<br />调用了它的父类Parcel的构造方法，设定它从Parcel中继承的变量寄出地址、寄达地址和重量的初值。这就是我们在前面提到过的super变量在构造方法中的用途：调用父类的相应构造方法。这样做的一个好处是可以重用父类的代码，然后PostParcel就只需设定邮资，并将posted和postable初值都置为false。<br />　　PostParcel和PostRemit都实现了接口MailPost，国而在它们的定义中，都必须给出方法calPrice()和post()的具体实现。在PostParcel中，为了简单起见，邮费只是根据重量每克收到0.05元，而不考虑寄达的距离，如语句第15行：<br />　　　　return ((float)0.05*weight);<br />在post()方法中，将计算所得邮资与瑞有邮费加以比较，若邮费已够将postable设为true，包裹可邮寄；否则postable为false，包裹不可邮寄。无论postable取值如何，都已试图邮寄，所以将posted置为true。处理过程见第18行至20行。<br />　　最后一个方法是showMe()。在这里，PostParcel重写(Overriding)了它的父类Parcel中的同名方法。当包裹尚未被试图邮寄过，则在基本信息后附加有关的邮寄信息，若未邮寄成功，给出所需最费提示。<br />　　PostRemit类的基本构成与PostParcel是一致的，读者可以自己试着读懂它的源文件。<br />　　在包ch4package中，类Mails，Parcel，Remittance以及ShowMails都无需改动，只有最后的可执行类Show需要相应的修改。它的源程序如下。<br />　　例4.13 可执行类Show程序文件。<br />　　-------------------------<br />//Show.<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b><br /><br />　　1: package ch4package;<br />import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.lang.*;<br />　　2: import <b style="COLOR: black; BACKGROUND-COLOR: #ffff66">java</b>.io.*;<br />　　3:<br />　　4: public class Show{<br />　　5:　public static ShowMails board=new ShowMails();<br />　　6:　　public static void main(String args[])throws IOException{<br />　　7: 　　　boolean finished=false;<br />　　8:　　　BufferedReader in =new BufferedReader(new InputStreamReader(System.in));<br />　　9:　　　while(!finished){//添加邮件<br />　　10:　　　　System.out.print("\nDo you want to add mails(Y/N)?");<br />　　11:　　　　System.out.flush();<br />　　12:　　　　char ch=in.readLine().charAt(0);<br />　　13:　　　　if('Y'==Character.toUpperCase(ch)){<br />　　14:　　　　System.out.println("Address information:");<br />　　15:　　　　System.out.print("\tFrom:");//输入地址信息<br />　　16:　　　　System.out.flush();<br />　　17:　　　　String address1=in.readLine();<br />　　18:　　　　System.out.print("\tTo:");<br />　　19:　　　　System.out.flush();<br />　　20:　　　　String address2=in.readLine();<br />　　　　　　//选择邮件种类<br />　　21:　　　　System.out.print("Choose the mail type:1-Parcel<br />2-Remittance ");<br />　　22:　　　　System.out.flush();<br />　　23:　　　　ch=in.readLine().charAt(0);<br />　　24:　　　　if('1'==ch){//输入包裹重量<br />　　25:　　　　　System.out.print("Parcel\tWeight:");<br />　　26:　　　　　System.out.flush();<br />　　27:　　　　　int w=getInt();<br />//是否寄出邮件<br />System.out.print("Do you want to post it(Y/N?");<br />System.out.flush();<br />ch=in.readLine().charAt(0);<br />if('Y'==Character.toUpperCase(ch)){//输入邮资<br />System.out.println("You want to post in,then<br />input your postage:");<br />System.out.flush();<br />int p=getInt();<br />//可邮寄包裹<br />PostParcel pa=new<br />PostParcel(address1,address2,w,p);<br />board.putMails(pa);<br />}<br />//不可邮寄包裹<br />else{Parcel pa=new Parcel(address1,address2,w);<br />board.putMails(pa);}<br />}<br />if('2'==ch){<br />System.out.print("Remittance\tMoney:");<br />System.out.flush();<br />int m=getInt();<br />System.out.print("Do you want to post it(Y/N)?");<br />System.out.flush():<br />ch=in.readLine().charAt(0);<br />if('Y'==Character.toUpperCase(ch)){<br />System.out.println("You want to post it,then input<br />postage:");<br />System.out.flush();<br />int p=getInt();<br />//可邮寄汇款<br />PostRemit re=new PostRemit(address1,address2,m,p);<br />board.putMails(re);<br />}<br />//不可邮寄汇款<br />else{Remittance re=new Remittance(address1,address2,m);<br />board.putMails(re);}<br />}<br />}<br />else finished=true;<br />}<br />System.out.println("");<br />board.showAll();//显示邮件信息<br />post();<br />}<br />public static int getInt() throws IEOxception{<br />BufferedReader in=new BufferedReader<br />(new InputStreamReader(System.in));<br />String st=in.readLine();<br />Integer i=new Integer(st);<br />return i.intValue();<br />}<br />private static void post()throws ClassCastException,IOException{<br />int n\board.mailnum();<br />if(n!=0){<br />System.out.println("You have "+n+" mails");<br />boolean end=false;<br />//检查邮寄情况<br />while(!end){<br />System.out.print("\nInput the mail NO you want to check the<br />result(输0退出):");<br />System.out.flush();<br />int i=getInt();<br />if(i!=0){<br />try{<br />Mails obj=board.getMails(i-1);<br />post((MailPost)obj);<br />obj.showMe();<br />}catch(ClassCastException ex){<br />System.out.println("Mail is not postable!");}<br />}<br />else end=true;<br />}<br />}<br />}<br />private static void post(MailPost obj){<br />obj.calPrice();<br />obj.post();<br />}<br />}<br />　　-------------------------<br />　　与第三节例4.8中类的Show相比，改动后的Show的main方法增加了询问是否要将邮件设为可邮寄类型的功能以及相应的处理段，并调用Post()方法邮寄邮件并给出邮寄情况说明。类Show定义了两个post方法来实惠邮寄。这两个方法虽同名，但参数不同，完成的功能也大相径庭。<br />　　第72行至92行的第一个post方法没有参数。它首先给出现有邮件数量，然后根据输入的邮件号通过ShowMails的getMails方法取得邮件，再调用第二个post方法实际将邮件寄出；当输入的邮件号为零时结束。在调用第二个post方法时，需要将邮件显式转换为接口类MailPost:<br />　　83:Mails obj=bord.getMails(i-1);<br />　　84:post((MailPost)obj);<br />因为PostParcel和PostRemit都实现了接口MailPost，都支持这样的转换，就可以通过种形式从功能上将它们统一起来。如果该邮件所属的类没有实现接口MailPost ,如类Parcel或类Remittance，这样的类型转换就不能实现，将引发类型转换异常(ClassCastException)，不再转去调用post方法，而由catch结构给出“邮件无法被邮寄”的报错信息：<br />　　86:}catch(ClassCastException ex){<br />　　87:　System.out.println("Mail is not postable!");}<br />其中的try-catch结构是<b style="COLOR: black; BACKGROUND-COLOR: #ffff66">Java</b>中异常处理的典型结构。<br />　　第二个post方法带一个MailPost接口类的参数，它实际调用接口定义的方法calPrice和post将邮件寄出。<br />　　下面我们来看一个Show的执行实例，其中带下划线“_”的部分为执行的键盘输入。<br />　　例4.14　Show的执行结果。<br />　　--------------------<br />　　--------------------<br />　　当启动Show的运行后，首先依照提示创建三个邮件对象，其中第一个是不可邮寄包裹后两个分别是可邮寄的包裹和汇款。停止添加邮件后顺序显示现有邮件信息，包括邮件号、邮件类别、地址信息、重量／金额以及已付邮资，并提示现有邮件总数。此时我们可依次检查邮件是否可寄出：<br />　　输入邮件号“１”，由于此包裹不是可邮寄包裹类，给出报告：邮件不可寄出；<br />　　输入邮件号“２”，该邮件是可邮寄包裹，且通过邮资计算已付足，给出报告：邮件可寄出；<br />　　输入邮件号“３”，该邮件是可邮寄汇款，但欠缺邮资，给出报告：邮件需补足邮资，然后列出应交邮费与实交邮费比较。<br />　　最后输入数字“０”，结束本次执行。<br />　　这样我们就完成了对第三节中邮件类的扩充和改进，最终得到的包ch4package中所有类和接口的层次继承关系，如图4.2所示。读者可以对照这个图理清它们的继承和实现关系。<br />　　　　　　　　　　　　　Object<br />　　　　　　　　┌─────┼─────┐<br />　　　　　　　　↓　　　　　↓　　　　　↓<br />　　　　　　　Mails　　ShowMails　　show<br />　　　　┌───┴───┐<br />　　　　↓　　　　　　　↓<br />　　　Parcel　　　　Remittance<br />　　　　↓　　　　　　　↓<br />　　PostParcel　　PostRemit<br />　　　　　　↖　　↗<br />　　　　　　MailPost<br />　　　　图4.2 包ch4package的类和接口层次</p><img src ="http://www.blogjava.net/19851985lili/aggbug/97637.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-02-02 20:26 <a href="http://www.blogjava.net/19851985lili/articles/97637.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>JavaScript 全角半角转换问题 </title><link>http://www.blogjava.net/19851985lili/articles/97636.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Fri, 02 Feb 2007 12:25:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/97636.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/97636.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/97636.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/97636.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/97636.html</trackback:ping><description><![CDATA[
		<div class="textbox-title">
				<h1>JavaScript 全角半角转换问题 </h1>
		</div>
		<div class="textbox-content">
				<div class="problem">问题 <span class="ptime">于 2006-09-14 14:02</span></div>
				<div class="con">&lt;script language=<a class="keyurl" href="http://www.it130.net/JAVA/index.htm" target="_blank">JAVA</a>script&gt;<br />var s="b";<br />var strCode<br />for(var i=0;i&lt;s.length;i++)<br />{<br />strCode=s.charCodeAt(i);<br />if((strCode&gt;65248)||(strCode==12288))<br />{<br />alert("有全角");<br />break;<br />}<br /><br />}<br />&lt;/script&gt;<br />半角字符由一个字节保存，全角字符用两个字节保存<br />所以码值的绝对值小于256的就是半角，否则就是全角<br /><br />问题一：全角除了空格charCode是12288落在0~65248之间，还有哪些在字符也落在这个区间之内？<br />问题二:如果用正则<br />&lt;script language="<a class="keyurl" href="http://www.it130.net/JAVA/index.htm" target="_blank">JAVA</a>script"&gt;<br />function go(obj){<br />obj.value=obj.value.replace(/([^\x00-\xff])/g,function($1){return String.fromCharCode($1.charCodeAt(0)-65248)});<br />}<br />由于正则不管是八进制（最多3位），16进制（2位）如果输入的是全半角混编的怎么办？ 
<div><script type="text/javascript"><!--
google_ad_client = "pub-1790048397430834";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel ="3321209211";
google_color_border = "FFFFFF";
google_color_bg = "FFFFFF";
google_color_link = "0000CC";
google_color_url = "008000";
google_color_text = "000000";
//--></script><script src="" type="text/javascript"></script></div></div>
				<!---->
				<div class="ans">响应者 <span class="num">1</span>:</div>
				<div class="con">第一个问题，你的范围有问题，<br />&lt;script language=<a class="keyurl" href="http://www.it130.net/JAVA/index.htm" target="_blank">JAVA</a>script&gt;<br />function DBC2SBC(str)<br />{<br /><br />var result = '';<br />for(var i=0;i&lt;str.length;i++){<br />code = str.charCodeAt(i);//获取当前字符的unicode编码<br />if (code &gt;= 65281 &amp;&amp; code &lt;= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符<br />{<br />result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码<br />}else if (code == 12288)//空格<br />{<br />result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);<br />}else<br />{<br />result += str.charAt(i);<br />}<br />}<br />return result;<br />}<br />alert(DBC2SBC("ＦＳＤＦＳＤＧ广泛豆腐干"))<br />&lt;/script&gt;<br /><br /><br />下面的这段是我自己猜测的<br />全角转半角<br /><a class="keyurl" href="http://www.it130.net/JAVA/index.htm" target="_blank">JAVA</a>script 是16位编码<br />65281到65373只有这里面的数据才是全角，这里要有范围限制的<br />关于65281的算法是这么来的<br />比如全角的字符Ａ<br />编码为FF21<br />转成16进制是<br />1111 1111 0010 0001<br />对两个字节分别取10进制的值<br />第一个字节是<br />65280<br />第二个自己是<br />33<br />所以a的65313<br /><br />对这个编码减去<br />65248得半角的<br /><br />65248比65280小32<br />所以我想ASC码小于32的就不能转换<br />因为转换了字符编码的前一字节就不能是1111 1111即FF<br />就会比这个小，那应该就不是全角了<br />就是说第一字节不能满足全为1<br /><br /><br />而你的第二个问题，根本不用考虑混用的时候<br />因为<br />replace的第一个参数正则会区分开的 </div>
				<!---->
				<div class="ans">响应者 <span class="num">2</span>:</div>
				<div class="con">就第一个问题shift+$在全角下输出为￥其CharCode为65509已经超出范围<br />我知道这个范围是code &gt;= 65281 &amp;&amp; code &lt;= 65373对于￥这样的符号又<br />怎么办？<br /><br />第二个问题，replace会区分全角半角？怎么区分？ </div>
				<!---->
				<div class="ans">响应者 <span class="num">3</span>:</div>
				<div class="con">function ToDBC(obj)//全角转半角<br />{ <br />var str=obj.value;<br />var result="";<br />for (var i = 0; i &lt; str.length; i++)<br />{<br />if (str.charCodeAt(i)==12288)<br />{<br />result+= String.fromCharCode(str.charCodeAt(i)-12256);<br />continue;<br />}<br />if (str.charCodeAt(i)&gt;65280 &amp;&amp; str.charCodeAt(i)&lt;65375)<br />result+= String.fromCharCode(str.charCodeAt(i)-65248);<br />else result+= String.fromCharCode(str.charCodeAt(i));<br />} <br />obj.value=result;<br />} </div>
				<!---->
				<!---->
		</div>
<img src ="http://www.blogjava.net/19851985lili/aggbug/97636.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-02-02 20:25 <a href="http://www.blogjava.net/19851985lili/articles/97636.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>VB.net中全角半角转换方法</title><link>http://www.blogjava.net/19851985lili/articles/97633.html</link><dc:creator>☜♥☞MengChuChen</dc:creator><author>☜♥☞MengChuChen</author><pubDate>Fri, 02 Feb 2007 12:19:00 GMT</pubDate><guid>http://www.blogjava.net/19851985lili/articles/97633.html</guid><wfw:comment>http://www.blogjava.net/19851985lili/comments/97633.html</wfw:comment><comments>http://www.blogjava.net/19851985lili/articles/97633.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/19851985lili/comments/commentRss/97633.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/19851985lili/services/trackbacks/97633.html</trackback:ping><description><![CDATA[**/<span id="Codehighlighter1_2_234_Open_Text"><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;summary&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> 转全角的函数(SBC case)<br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;/summary&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;param name="input"&gt;</span><span style="COLOR: #008000">任意字符串</span><span style="COLOR: #808080">&lt;/param&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;returns&gt;</span><span style="COLOR: #008000">全角字符串</span><span style="COLOR: #808080">&lt;/returns&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #808080">&lt;remarks&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000">全角空格为12288，半角空格为32<br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000">其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248<br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #808080">&lt;/remarks&gt;</span><span style="COLOR: #008000">        </span><span style="COLOR: #808080"></span></span><br /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><span style="COLOR: #000000">        </span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000"> ToSBC(</span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000"> input)<br />        </span><span id="Codehighlighter1_273_515_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"></span><span id="Codehighlighter1_273_515_Open_Text"><span style="COLOR: #000000">{<br />            </span><span style="COLOR: #008000">//</span><span style="COLOR: #008000">半角转全角：</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #000000">            </span><span style="COLOR: #0000ff">char</span><span style="COLOR: #000000">[] c</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">input.ToCharArray();<br />            </span><span style="COLOR: #0000ff">for</span><span style="COLOR: #000000"> (</span><span style="COLOR: #0000ff">int</span><span style="COLOR: #000000"> i </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">; i </span><span style="COLOR: #000000">&lt;</span><span style="COLOR: #000000"> c.Length; i</span><span style="COLOR: #000000">++</span><span style="COLOR: #000000">)<br />            </span><span id="Codehighlighter1_361_482_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"></span><span id="Codehighlighter1_361_482_Open_Text"><span style="COLOR: #000000">{<br />                </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> (c[i]</span><span style="COLOR: #000000">==</span><span style="COLOR: #000000">32</span><span style="COLOR: #000000">)<br />                </span><span id="Codehighlighter1_385_429_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"></span><span id="Codehighlighter1_385_429_Open_Text"><span style="COLOR: #000000">{<br />                    c[i]</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">(</span><span style="COLOR: #0000ff">char</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">12288</span><span style="COLOR: #000000">;<br />                    </span><span style="COLOR: #0000ff">continue</span><span style="COLOR: #000000">;<br />                }</span></span><span style="COLOR: #000000"><br />                </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> (c[i]</span><span style="COLOR: #000000">&lt;</span><span style="COLOR: #000000">127</span><span style="COLOR: #000000">)<br />                    c[i]</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">(</span><span style="COLOR: #0000ff">char</span><span style="COLOR: #000000">)(c[i]</span><span style="COLOR: #000000">+</span><span style="COLOR: #000000">65248</span><span style="COLOR: #000000">);<br />            }</span></span><span style="COLOR: #000000"><br />            </span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">new</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000">(c);                <br />        }</span></span><span style="COLOR: #000000"><br /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><br /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><br />        </span><span id="Codehighlighter1_521_751_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff">/**/</span><span id="Codehighlighter1_521_751_Open_Text"><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;summary&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> 转半角的函数(DBC case)<br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;/summary&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;param name="input"&gt;</span><span style="COLOR: #008000">任意字符串</span><span style="COLOR: #808080">&lt;/param&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000"> </span><span style="COLOR: #808080">&lt;returns&gt;</span><span style="COLOR: #008000">半角字符串</span><span style="COLOR: #808080">&lt;/returns&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #808080">&lt;remarks&gt;</span><span style="COLOR: #008000"><br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000">全角空格为12288，半角空格为32<br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #008000">其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248<br />        </span><span style="COLOR: #808080">///</span><span style="COLOR: #808080">&lt;/remarks&gt;</span><span style="COLOR: #808080"></span></span><br /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><span style="COLOR: #000000">        </span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000"> ToDBC(</span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000"> input)<br />        </span><span id="Codehighlighter1_790_1035_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"></span><span id="Codehighlighter1_790_1035_Open_Text"><span style="COLOR: #000000">{    <br />            </span><span style="COLOR: #0000ff">char</span><span style="COLOR: #000000">[] c</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">input.ToCharArray();<br />            </span><span style="COLOR: #0000ff">for</span><span style="COLOR: #000000"> (</span><span style="COLOR: #0000ff">int</span><span style="COLOR: #000000"> i </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">; i </span><span style="COLOR: #000000">&lt;</span><span style="COLOR: #000000"> c.Length; i</span><span style="COLOR: #000000">++</span><span style="COLOR: #000000">)<br />            </span><span id="Codehighlighter1_867_1005_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"></span><span id="Codehighlighter1_867_1005_Open_Text"><span style="COLOR: #000000">{<br />                </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> (c[i]</span><span style="COLOR: #000000">==</span><span style="COLOR: #000000">12288</span><span style="COLOR: #000000">)<br />                </span><span id="Codehighlighter1_894_936_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"></span><span id="Codehighlighter1_894_936_Open_Text"><span style="COLOR: #000000">{<br />                    c[i]</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> (</span><span style="COLOR: #0000ff">char</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">32</span><span style="COLOR: #000000">;<br />                    </span><span style="COLOR: #0000ff">continue</span><span style="COLOR: #000000">;<br />                }</span></span><span style="COLOR: #000000"><br />                </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> (c[i]</span><span style="COLOR: #000000">&gt;</span><span style="COLOR: #000000">65280</span><span style="COLOR: #000000"> </span><span style="COLOR: #000000">&amp;&amp;</span><span style="COLOR: #000000"> c[i]</span><span style="COLOR: #000000">&lt;</span><span style="COLOR: #000000">65375</span><span style="COLOR: #000000">)<br />                    c[i]</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">(</span><span style="COLOR: #0000ff">char</span><span style="COLOR: #000000">)(c[i]</span><span style="COLOR: #000000">-</span><span style="COLOR: #000000">65248</span><span style="COLOR: #000000">);<br />            }</span></span><span style="COLOR: #000000">    <br />            </span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">new</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000">(c);<br />        }</span></span><span style="COLOR: #000000"><br /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />2.C#中直接调用VB.NET的函数，兼论半角与全角、简繁体中文互相转化 </span><p><span style="COLOR: #000000"><span style="FONT-SIZE: 10pt; FONT-FAMILY: Lucida Console">在C#项目中添加引用Microsoft.VisualBasic.dll, 可以在C#程序中直接使用VB.NET中丰富的函数 </span></span></p><div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #008080"> 1</span><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 命令行编译 : csc /r:Microsoft.VisualBasic.dll Test.cs<br /></span><span style="COLOR: #008080"> 2</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><br /></span><span style="COLOR: #008080"> 3</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 如果是用 Visual Studio .NET IDE, 请按以下方法为项目添加引用:<br /></span><span style="COLOR: #008080"> 4</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 打开[解决方案资源管理器], 右击项目名称, 选择[添加引用],<br /></span><span style="COLOR: #008080"> 5</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 从列表中选择 Microsoft Visual Basic .NET Runtime 组件.</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #008080"> 6</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #000000"><br /></span><span style="COLOR: #008080"> 7</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #0000ff">using</span><span style="COLOR: #000000"> Microsoft.VisualBasic;<br /></span><span style="COLOR: #008080"> 8</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><br /></span><span style="COLOR: #008080"> 9</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #0000ff">class</span><span style="COLOR: #000000"> Test<br /></span><span style="COLOR: #008080">10</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span id="Codehighlighter1_228_753_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" /></span><span id="Codehighlighter1_228_753_Open_Text"><span style="COLOR: #000000">{<br /></span><span style="COLOR: #008080">11</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />  </span><span style="COLOR: #0000ff">static</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">void</span><span style="COLOR: #000000"> Main()<br /></span><span style="COLOR: #008080">12</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />  </span><span id="Codehighlighter1_253_751_Closed_Text" style="BORDER-RIGHT: #808080 1px solid; BORDER-TOP: #808080 1px solid; DISPLAY: none; BORDER-LEFT: #808080 1px solid; BORDER-BOTTOM: #808080 1px solid; BACKGROUND-COLOR: #ffffff"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" /></span><span id="Codehighlighter1_253_751_Open_Text"><span style="COLOR: #000000">{<br /></span><span style="COLOR: #008080">13</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />    </span><span style="COLOR: #0000ff">string</span><span style="COLOR: #000000"> s </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">博客园-空军 [skyIV.cnBlogs.com]</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">;<br /></span><span style="COLOR: #008080">14</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />    System.Console.WriteLine(s);<br /></span><span style="COLOR: #008080">15</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />    s </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> Strings.StrConv(s, VbStrConv.Wide              , </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">); </span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 半角转全角</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #008080">16</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #000000">    s </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> Strings.StrConv(s, VbStrConv.TraditionalChinese, </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">); </span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 简体转繁体</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #008080">17</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #000000">    System.Console.WriteLine(s);<br /></span><span style="COLOR: #008080">18</span><span style="COLOR: #000000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" />    s </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> Strings.StrConv(s, VbStrConv.ProperCase        , </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">); </span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 首字母大写</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #008080">19</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #000000">    s </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> Strings.StrConv(s, VbStrConv.Narrow            , </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">); </span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 全角转半角</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #008080">20</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #000000">    s </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> Strings.StrConv(s, VbStrConv.SimplifiedChinese , </span><span style="COLOR: #000000">0</span><span style="COLOR: #000000">); </span><span style="COLOR: #008000">//</span><span style="COLOR: #008000"> 繁体转简体</span><span style="COLOR: #008000"><br /></span><span style="COLOR: #008080">21</span><span style="COLOR: #008000"><img style="CURSOR: pointer" onclick="javascript:window.open(this.src);" src="" onload="javascript:if(this.width&gt;500){this.resized=true;this.style.width=500;}" align="top" /></span><span style="COLOR: #000000">    System.Console.WriteLine(s);<br /></span></span></span></div><img src ="http://www.blogjava.net/19851985lili/aggbug/97633.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/19851985lili/" target="_blank">☜♥☞MengChuChen</a> 2007-02-02 20:19 <a href="http://www.blogjava.net/19851985lili/articles/97633.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>