﻿<?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-EricGu's Java-Record-Space</title><link>http://www.blogjava.net/EricGu/</link><description>专注 学习 实践 创新</description><language>zh-cn</language><lastBuildDate>Wed, 15 Apr 2026 12:10:26 GMT</lastBuildDate><pubDate>Wed, 15 Apr 2026 12:10:26 GMT</pubDate><ttl>60</ttl><item><title>ora10ginstant 精简客户端遇到 system.data.oracleclient 需要 oracle 客户端软件8.1.7 或更高版本</title><link>http://www.blogjava.net/EricGu/archive/2012/04/19/375255.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Thu, 19 Apr 2012 05:09:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2012/04/19/375255.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/375255.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2012/04/19/375255.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/375255.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/375255.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 遇到System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本。一般第一反映都是会出处理&nbsp; oracle_home 文件夹权限。可是有时时候 不管你怎么摆弄权限，怎么iisreset，怎么重启电脑都解决不了，cmd&nbsp; path 明明可以看到有oracle_home 路径啊。问题在于。环境变量中， ora10gInstant 精简客户端默认把变量添加到 Administrator 的用户变量了，我们要做的是把&nbsp; 用户变量中的 Path 值 转到 系统变量中的 Path 中。<img src ="http://www.blogjava.net/EricGu/aggbug/375255.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2012-04-19 13:09 <a href="http://www.blogjava.net/EricGu/archive/2012/04/19/375255.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用 spring 2.5 注释驱动的 ioc 功能 </title><link>http://www.blogjava.net/EricGu/archive/2010/12/15/340791.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Wed, 15 Dec 2010 06:40:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2010/12/15/340791.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/340791.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2010/12/15/340791.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/340791.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/340791.html</trackback:ping><description><![CDATA[<div class="blog_content">
<blockquote>
<p>在项目中使用Spring的注解，关于spring的注解，由两种注解方式，</p>
<p>基于注释（Annotation）的配置有越来越流行的趋势，Spring 2.5 顺应这种趋势，提供了完全基于注释配置 Bean、装配 Bean 的功能，您可以使用基于注释的 Spring IoC 替换原来基于 XML 的配置。本文通过实例详细讲述了 Spring 2.5 基于注释 IoC 功能的使用。</p>
</blockquote>&lt;!--START RESERVED FOR FUTURE USE INCLUDE FILES--&gt;&lt;!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters --&gt;&lt;!--END RESERVED FOR FUTURE USE INCLUDE FILES--&gt;
<p><a name="N1004A"><span class="atitle"><strong><span style="font-size: large">概述</span></strong></span></a></p>
<p>注释配置相对于 XML 配置具有很多的优势：</p>
<ul>
    <li>它可以充分利用 Java 的反射机制获取类结构信息，这些信息可以有效减少配置的工作。如使用 JPA 注释配置 ORM 映射时，我们就不需要指定 PO 的属性名、类型等信息，如果关系表字段和 PO 属性名、类型都一致，您甚至无需编写任务属性映射信息——因为这些信息都可以通过 Java 反射机制获取。 </li>
    <li>注释和 Java 代码位于一个文件中，而 XML 配置采用独立的配置文件，大多数配置信息在程序开发完成后都不会调整，如果配置信息和 Java 代码放在一起，有助于增强程序的内聚性。而采用独立的 XML 配置文件，程序员在编写一个功能时，往往需要在程序文件和配置文件中不停切换，这种思维上的不连贯会降低开发效率。 </li>
</ul>
<p>因此在很多情况下，注释配置比 XML 配置更受欢迎，注释配置有进一步流行的趋势。Spring 2.5 的一大增强就是引入了很多注释类，现在您已经可以使用注释配置完成大部分 XML 配置的功能。在这篇文章里，我们将向您讲述使用注释进行 Bean 定义和依赖注入的内容。</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><a name="N100A7"><span class="atitle"><strong><span style="font-size: large">使用 @Autowired 注释</span></strong></span></a></p>
<p>Spring 2.5 引入了 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 注释，它可以对类成员变量、方法及构造函数进行标注，完成自动装配的工作。</p>
<p>Spring 通过一个 <code><span style="font-family: Courier; font-size: x-small">BeanPostProcessor</span></code> 对 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 进行解析，所以要让 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 起作用必须事先在 Spring 容器中声明 <code><span style="font-family: Courier; font-size: x-small">AutowiredAnnotationBeanPostProcessor</span></code> Bean。</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>在Spring中配置如下：</p>
<p>&lt;!-- 该 BeanPostProcessor 将自动起作用，对标注 @Autowired 的 Bean 进行自动注入 --&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;bean class="org.springframework.beans.factory.annotation.<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AutowiredAnnotationBeanPostProcessor"/&gt;<br />
当 Spring 容器启动时，<code><span style="font-family: Courier; font-size: x-small">AutowiredAnnotationBeanPostProcessor</span></code> 将扫描 Spring 容器中所有 Bean，当发现 Bean 中拥有 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 注释时就找到和其匹配（默认按类型匹配）的 Bean，并注入到对应的地方中去。</p>
<p>按照上面的配置，Spring 将直接采用 Java 反射机制对 Boss 中的 <code><span style="font-family: Courier; font-size: x-small">car</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">office</span></code> 这两个私有成员变量进行自动注入。所以对成员变量使用 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 后，您大可将它们的 setter 方法（<code><span style="font-family: Courier; font-size: x-small">setCar()</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">setOffice()</span></code>）从 Boss 中删除。</p>
<p>当然，您也可以通过 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 对方法或构造函数进行标注，</p>
<p>&nbsp;</p>
<p><a name="N10139"><span class="atitle"><strong><span style="font-size: large">当候选 Bean 数目不为 1 时的应对方法</span></strong></span></a></p>
<p>在默认情况下使用 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 注释进行自动注入时，Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时，Spring 容器将抛出 <code><span style="font-family: Courier; font-size: x-small">BeanCreationException</span></code> 异常，并指出必须至少拥有一个匹配的 Bean。</p>
<p>&nbsp;</p>
<p>当不能确定 Spring 容器中一定拥有某个类的 Bean 时，可以在需要自动注入该类 Bean 的地方可以使用 <code><span style="font-family: Courier; font-size: x-small">@Autowired(required = false)</span></code>，这等于告诉 Spring：在找不到匹配 Bean 时也不报错。</p>
<p>&nbsp;</p>
<p>一般情况下，使用 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 的地方都是需要注入 Bean 的，使用了自动注入而又允许不注入的情况一般仅会在开发期或测试期碰到（如为了快速启动 Spring 容器，仅引入一些模块的 Spring 配置文件），所以 <code><span style="font-family: Courier; font-size: x-small">@Autowired(required = false)</span></code> 会很少用到。</p>
<p>和找不到一个类型匹配 Bean 相反的一个错误是：如果 Spring 容器中拥有多个候选 Bean，Spring 容器在启动时也会抛出 <code><span style="font-family: Courier; font-size: x-small">BeanCreationException</span></code> 异常。</p>
<p>&nbsp;</p>
<p>Spring 允许我们通过 <code><span style="font-family: Courier; font-size: x-small">@Qualifier</span></code> 注释指定注入 Bean 的名称，这样歧义就消除了，可以通过下面的方法解决异常：</p>
<p><br />
<a name="N101A5"><strong>清单 13. 使用 @Qualifier 注释指定注入 Bean 的名称</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            @Autowired
            public void setOffice(@Qualifier("office")Office office) {
            this.office = office;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p><code><span style="font-family: Courier; font-size: x-small">@Qualifier("office")</span></code> 中的 <code><span style="font-family: Courier; font-size: x-small">office</span></code> 是 Bean 的名称，所以 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">@Qualifier</span></code> 结合使用时，自动注入的策略就从 byType 转变成 byName 了。<code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 可以对成员变量、方法以及构造函数进行注释，而 <code><span style="font-family: Courier; font-size: x-small">@Qualifier</span></code> 的标注对象是成员变量、方法入参、构造函数入参。正是由于注释对象的不同，所以 Spring 不将 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">@Qualifier</span></code> 统一成一个注释类。下面是对成员变量和构造函数入参进行注释的代码：</p>
<p>对成员变量进行注释：</p>
<p>&nbsp;</p>
<p><strong>对成员变量使用 @Qualifier 注释<br />
</strong></p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            public class Boss {
            @Autowired
            private Car car;
            @Autowired
            @Qualifier("office")
            private Office office;
            &#8230;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>对构造函数入参进行注释：</p>
<p><br />
<a name="N101E0"><strong>清单 15. 对构造函数变量使用 @Qualifier 注释</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            public class Boss {
            private Car car;
            private Office office;
            @Autowired
            public Boss(Car car , @Qualifier("office")Office office){
            this.car = car;
            this.office = office ;
            }
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p><code><span style="font-family: Courier; font-size: x-small">@Qualifier</span></code> 只能和 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 结合使用，是对 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 有益的补充。一般来讲，<code><span style="font-family: Courier; font-size: x-small">@Qualifier</span></code> 对方法签名中入参进行注释会降低代码的可读性，而对成员变量注释则相对好一些。</p>
<p>&nbsp;</p>
<p><a name="N101F9"><span class="atitle"><strong><span style="font-size: large">使用 JSR-250 的注释</span></strong></span></a></p>
<p>Spring 不但支持自己定义的 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 的注释，还支持几个由 JSR-250 规范定义的注释，它们分别是 <code><span style="font-family: Courier; font-size: x-small">@Resource</span></code>、<code><span style="font-family: Courier; font-size: x-small">@PostConstruct</span></code> 以及 <code><span style="font-family: Courier; font-size: x-small">@PreDestroy</span></code>。</p>
<p><a name="N10211"><span class="smalltitle"><strong><span style="font-size: small">@Resource</span></strong></span></a></p>
<p><code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 的作用相当于 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code>，只不过 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 按 byType 自动注入，面 <code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 默认按 byName 自动注入罢了。<code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 有两个属性是比较重要的，分别是 name 和 type，Spring 将 <code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 注释的 name 属性解析为 Bean 的名字，而 type 属性则解析为 Bean 的类型。所以如果使用 name 属性，则使用 byName 的自动注入策略，而使用 type 属性时则使用 byType 自动注入策略。如果既不指定 name 也不指定 type 属性，这时将通过反射机制使用 byName 自动注入策略。</p>
<p>Resource 注释类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中，因此在使用之前必须将其加入到项目的类库中。来看一个使用 <code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 的例子：</p>
<p><br />
<a name="N1023B"><strong>清单 16. 使用 @Resource 注释的 Boss.java</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import javax.annotation.Resource;
            public class Boss {
            // 自动注入类型为 Car 的 Bean
            @Resource
            private Car car;
            // 自动注入 bean 名称为 office 的 Bean
            @Resource(name = "office")
            private Office office;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>一般情况下，我们无需使用类似于 <code><span style="font-family: Courier; font-size: x-small">@Resource(type=Car.class)</span></code> 的注释方式，因为 Bean 的类型信息可以通过 Java 反射从代码中获取。</p>
<p>要让 JSR-250 的注释生效，除了在 Bean 类中标注这些注释外，还需要在 Spring 容器中注册一个负责处理这些注释的 <code><span style="font-family: Courier; font-size: x-small">BeanPostProcessor</span></code>：</p>
<p>&nbsp;</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">&lt;bean
            class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/&gt;
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p><code><span style="font-family: Courier; font-size: x-small">CommonAnnotationBeanPostProcessor</span></code> 实现了 <code><span style="font-family: Courier; font-size: x-small">BeanPostProcessor</span></code> 接口，它负责扫描使用了 JSR-250 注释的 Bean，并对它们进行相应的操作。</p>
<p><a name="N1025E"><span class="smalltitle"><strong><span style="font-size: small">@PostConstruct 和 @PreDestroy</span></strong></span></a></p>
<p>Spring 容器中的 Bean 是有生命周期的，Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作，您既可以通过实现 InitializingBean/DisposableBean 接口来定制初始化之后 / 销毁之前的操作方法，也可以通过 &lt;bean&gt; 元素的 init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法。关于 Spring 的生命周期，笔者在《精通 Spring 2.x—企业应用开发精解》第 3 章进行了详细的描述，有兴趣的读者可以查阅。</p>
<p>JSR-250 为初始化之后/销毁之前方法的指定定义了两个注释类，分别是 @PostConstruct 和 @PreDestroy，这两个注释只能应用于方法上。标注了 @PostConstruct 注释的方法将在类实例化后调用，而标注了 @PreDestroy 的方法将在类销毁之前调用。</p>
<p><br />
<a name="N1026C"><strong>清单 17. 使用 @PostConstruct 和 @PreDestroy 注释的 Boss.java</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import javax.annotation.Resource;
            import javax.annotation.PostConstruct;
            import javax.annotation.PreDestroy;
            public class Boss {
            @Resource
            private Car car;
            @Resource(name = "office")
            private Office office;
            @PostConstruct
            public void postConstruct1(){
            System.out.println("postConstruct1");
            }
            @PreDestroy
            public void preDestroy1(){
            System.out.println("preDestroy1");
            }
            &#8230;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>您只需要在方法前标注 <code><span style="font-family: Courier; font-size: x-small">@PostConstruct</span></code> 或 <code><span style="font-family: Courier; font-size: x-small">@PreDestroy</span></code>，这些方法就会在 Bean 初始化后或销毁之前被 Spring 容器执行了。</p>
<p>我们知道，不管是通过实现 <code><span style="font-family: Courier; font-size: x-small">InitializingBean</span></code>/<code><span style="font-family: Courier; font-size: x-small">DisposableBean</span></code> 接口，还是通过 &lt;bean&gt; 元素的 <code><span style="font-family: Courier; font-size: x-small">init-method/destroy-method</span></code> 属性进行配置，都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用 <code><span style="font-family: Courier; font-size: x-small">@PostConstruct</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">@PreDestroy</span></code> 注释却可以指定多个初始化 / 销毁方法，那些被标注 <code><span style="font-family: Courier; font-size: x-small">@PostConstruct</span></code> 或 <code><span style="font-family: Courier; font-size: x-small">@PreDestroy</span></code> 注释的方法都会在初始化 / 销毁时被执行。</p>
<p>通过以下的测试代码，您将可以看到 Bean 的初始化 / 销毁方法是如何被执行的：</p>
<p><br />
<a name="N102A2"><strong>清单 18. 测试类代码</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import org.springframework.context.support.ClassPathXmlApplicationContext;
            public class AnnoIoCTest {
            public static void main(String[] args) {
            String[] locations = {"beans.xml"};
            ClassPathXmlApplicationContext ctx =
            new ClassPathXmlApplicationContext(locations);
            Boss boss = (Boss) ctx.getBean("boss");
            System.out.println(boss);
            ctx.destroy();// 关闭 Spring 容器，以触发 Bean 销毁方法的执行
            }
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>这时，您将看到标注了 <code><span style="font-family: Courier; font-size: x-small">@PostConstruct</span></code> 的 <code><span style="font-family: Courier; font-size: x-small">postConstruct1()</span></code> 方法将在 Spring 容器启动时，创建 <code><span style="font-family: Courier; font-size: x-small">Boss</span></code> Bean 的时候被触发执行，而标注了 <code><span style="font-family: Courier; font-size: x-small">@PreDestroy</span></code> 注释的 <code><span style="font-family: Courier; font-size: x-small">preDestroy1()</span></code> 方法将在 Spring 容器关闭前销毁 <code><span style="font-family: Courier; font-size: x-small">Boss</span></code> Bean 的时候被触发执行。</p>
<p><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td><img class="magplus" title="点击查看原始大小图片" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="700" height="0" /><br />
            <img border="0" alt="" src="http://www.ibm.com/i/c.gif" width="8" height="6" /> </td>
        </tr>
    </tbody>
</table>
<table class="no-print" border="0" cellspacing="0" cellpadding="0" align="right">
    <tbody>
        <tr align="right">
            <td><img alt="" src="http://www.ibm.com/i/c.gif" width="100%" height="4" /><br />
            <table border="0" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td valign="middle"><img border="0" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" height="16" /><br />
                        </td>
                        <td valign="top" align="right"><a class="fbox" href="http://topmanopensource.javaeye.com/admin/blogs/#main"><strong><span style="color: #996699">回页首</span></strong></a></td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
<br />
<p><a name="N102C3"><span class="atitle"><strong><span style="font-size: large">使用 &lt;context:annotation-config/&gt; 简化配置</span></strong></span></a></p>
<p>Spring 2.1 添加了一个新的 context 的 Schema 命名空间，该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的，它仅提供元数据信息。要使元数据信息真正起作用，必须让负责处理这些元数据的处理器工作起来。 </p>
<p>而我们前面所介绍的 <code><span style="font-family: Courier; font-size: x-small">AutowiredAnnotationBeanPostProcessor</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">CommonAnnotationBeanPostProcessor</span></code> 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 <code><span style="font-family: Courier; font-size: x-small">BeanPostProcessor</span></code> 的方式，这就是 &lt;context:annotation-config/&gt;。请看下面的配置：</p>
<p><br />
<a name="N102DE"><strong>清单 19. 调整 beans.xml 配置文件</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            &lt;?xml version="1.0" encoding="UTF-8" ?&gt;
            &lt;beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-2.5.xsd"&gt;
            &lt;context:annotation-config/&gt;
            &lt;bean id="boss" class="com.baobaotao.Boss"/&gt;
            &lt;bean id="office" class="com.baobaotao.Office"&gt;
            &lt;property name="officeNo" value="001"/&gt;
            &lt;/bean&gt;
            &lt;bean id="car" class="com.baobaotao.Car" scope="singleton"&gt;
            &lt;property name="brand" value=" 红旗 CA72"/&gt;
            &lt;property name="price" value="2000"/&gt;
            &lt;/bean&gt;
            &lt;/beans&gt;
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>&lt;context:annotationconfig/&gt; 将隐式地向 Spring 容器注册 <code><span style="font-family: Courier; font-size: x-small">AutowiredAnnotationBeanPostProcessor</span></code>、<code><span style="font-family: Courier; font-size: x-small">CommonAnnotationBeanPostProcessor</span></code>、<code><span style="font-family: Courier; font-size: x-small">PersistenceAnnotationBeanPostProcessor</span></code> 以及 <code><span style="font-family: Courier; font-size: x-small">equiredAnnotationBeanPostProcessor</span></code> 这 4 个 BeanPostProcessor。</p>
<p>在配置文件中使用 context 命名空间之前，必须在 &lt;beans&gt; 元素中声明 context 命名空间。</p>
<p><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td><img class="magplus" title="点击查看原始大小图片" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="700" height="0" /><br />
            <img border="0" alt="" src="http://www.ibm.com/i/c.gif" width="8" height="6" /> </td>
        </tr>
    </tbody>
</table>
<table class="no-print" border="0" cellspacing="0" cellpadding="0" align="right">
    <tbody>
        <tr align="right">
            <td><img alt="" src="http://www.ibm.com/i/c.gif" width="100%" height="4" /><br />
            <table border="0" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td valign="middle"><img border="0" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" height="16" /><br />
                        </td>
                        <td valign="top" align="right"><a class="fbox" href="http://topmanopensource.javaeye.com/admin/blogs/#main"><strong><span style="color: #996699">回页首</span></strong></a></td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
<br />
<p><a name="N102FA"><span class="atitle"><strong><span style="font-size: large">使用 @Component</span></strong></span></a></p>
<p>虽然我们可以通过 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 或 <code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 在 Bean 类中使用自动注入功能，但是 Bean 还是在 XML 文件中通过 &lt;bean&gt; 进行定义 —— 也就是说，在 XML 配置文件中定义 Bean，通过 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 或 <code><span style="font-family: Courier; font-size: x-small">@Resource</span></code> 为 Bean 的成员变量、方法入参或构造函数入参提供自动注入的功能。能否也通过注释定义 Bean，从 XML 配置文件中完全移除 Bean 定义的配置呢？答案是肯定的，我们通过 Spring 2.5 提供的 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 注释就可以达到这个目标了。</p>
<p>下面，我们完全使用注释定义 Bean 并完成 Bean 之间装配：</p>
<p><br />
<a name="N1031C"><strong>清单 20. 使用 @Component 注释的 Car.java</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import org.springframework.stereotype.Component;
            @Component
            public class Car {
            &#8230;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>仅需要在类定义处，使用 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 注释就可以将一个类定义了 Spring 容器中的 Bean。下面的代码将 <code><span style="font-family: Courier; font-size: x-small">Office</span></code> 定义为一个 Bean：</p>
<p><br />
<a name="N10330"><strong>清单 21. 使用 @Component 注释的 Office.java</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import org.springframework.stereotype.Component;
            @Component
            public class Office {
            private String officeNo = "001";
            &#8230;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>这样，我们就可以在 Boss 类中通过 <code><span style="font-family: Courier; font-size: x-small">@Autowired</span></code> 注入前面定义的 <code><span style="font-family: Courier; font-size: x-small">Car</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">Office Bean</span></code> 了。</p>
<p><br />
<a name="N10348"><strong>清单 22. 使用 @Component 注释的 Boss.java</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.beans.factory.annotation.Required;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.stereotype.Component;
            @Component("boss")
            public class Boss {
            @Autowired
            private Car car;
            @Autowired
            private Office office;
            &#8230;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p><code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 有一个可选的入参，用于指定 Bean 的名称，在 Boss 中，我们就将 Bean 名称定义为&#8220;<code><span style="font-family: Courier; font-size: x-small">boss</span></code>&#8221;。一般情况下，Bean 都是 singleton 的，需要注入 Bean 的地方仅需要通过 byType 策略就可以自动注入了，所以大可不必指定 Bean 的名称。</p>
<p>在使用 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 注释后，Spring 容器必须启用类扫描机制以启用注释驱动 Bean 定义和注释驱动 Bean 自动注入的策略。Spring 2.5 对 context 命名空间进行了扩展，提供了这一功能，请看下面的配置：</p>
<p><br />
<a name="N10363"><strong>清单 23. 简化版的 beans.xml</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            &lt;?xml version="1.0" encoding="UTF-8" ?&gt;
            &lt;beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-2.5.xsd"&gt;
            &lt;context:component-scan base-package="com.baobaotao"/&gt;
            &lt;/beans&gt;
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>这里，所有通过 &lt;bean&gt; 元素定义 Bean 的配置内容已经被移除，仅需要添加一行 &lt;context:component-scan/&gt; 配置就解决所有问题了——Spring XML 配置文件得到了极致的简化（当然配置元数据还是需要的，只不过以注释形式存在罢了）。&lt;context:component-scan/&gt; 的 base-package 属性指定了需要扫描的类包，类包及其递归子包中所有的类都会被处理。</p>
<p>&lt;context:component-scan/&gt; 还允许定义过滤器将基包下的某些类纳入或排除。Spring 支持以下 4 种类型的过滤方式，通过下表说明：</p>
<p><br />
<a name="N1036F"><strong>表 1. 扫描过滤方式</strong></a><br />
</p>
<table class="data-table-1" border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <th width="20%">过滤器类型</th>
            <th width="80%">说明</th>
        </tr>
        <tr>
            <td>注释</td>
            <td>假如 com.baobaotao.SomeAnnotation 是一个注释类，我们可以将使用该注释的类过滤出来。</td>
        </tr>
        <tr>
            <td>类名指定</td>
            <td>通过全限定类名进行过滤，如您可以指定将 com.baobaotao.Boss 纳入扫描，而将 com.baobaotao.Car 排除在外。</td>
        </tr>
        <tr>
            <td>正则表达式</td>
            <td>通过正则表达式定义过滤的类，如下所示： com\.baobaotao\.Default.*</td>
        </tr>
        <tr>
            <td>AspectJ 表达式</td>
            <td>通过 AspectJ 表达式定义过滤的类，如下所示： com. baobaotao..*Service+</td>
        </tr>
    </tbody>
</table>
<p>下面是一个简单的例子：</p>
<p>&nbsp;</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">&lt;context:component-scan base-package="com.baobaotao"&gt;
            &lt;context:include-filter type="regex"
            expression="com\.baobaotao\.service\..*"/&gt;
            &lt;context:exclude-filter type="aspectj"
            expression="com.baobaotao.util..*"/&gt;
            &lt;/context:component-scan&gt;
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>值得注意的是 &lt;context:component-scan/&gt; 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能，同时还启用了注释驱动自动注入的功能（即还隐式地在内部注册了 <code><span style="font-family: Courier; font-size: x-small">AutowiredAnnotationBeanPostProcessor</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">CommonAnnotationBeanPostProcessor</span></code>），因此当使用 &lt;context:component-scan/&gt; 后，就可以将 &lt;context:annotation-config/&gt; 移除了。</p>
<p>默认情况下通过 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 定义的 Bean 都是 singleton 的，如果需要使用其它作用范围的 Bean，可以通过 <code><span style="font-family: Courier; font-size: x-small">@Scope</span></code> 注释来达到目标，如以下代码所示：</p>
<p><br />
<a name="N103CC"><strong>清单 24. 通过 @Scope 指定 Bean 的作用范围</strong></a><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">
            package com.baobaotao;
            import org.springframework.context.annotation.Scope;
            &#8230;
            @Scope("prototype")
            @Component("boss")
            public class Boss {
            &#8230;
            }
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<p>这样，当从 Spring 容器中获取 <code><span style="font-family: Courier; font-size: x-small">boss</span></code> Bean 时，每次返回的都是新的实例了。</p>
<p><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td><img class="magplus" title="点击查看原始大小图片" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="700" height="0" /><br />
            <img border="0" alt="" src="http://www.ibm.com/i/c.gif" width="8" height="6" /> </td>
        </tr>
    </tbody>
</table>
<table class="no-print" border="0" cellspacing="0" cellpadding="0" align="right">
    <tbody>
        <tr align="right">
            <td><img alt="" src="http://www.ibm.com/i/c.gif" width="100%" height="4" /><br />
            <table border="0" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td valign="middle"><img border="0" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" height="16" /><br />
                        </td>
                        <td valign="top" align="right"><a class="fbox" href="http://topmanopensource.javaeye.com/admin/blogs/#main"><strong><span style="color: #996699">回页首</span></strong></a></td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
<br />
<p><a name="N103D9"><span class="atitle"><strong><span style="font-size: large">采用具有特殊语义的注释</span></strong></span></a></p>
<p>Spring 2.5 中除了提供 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 注释外，还定义了几个拥有特殊语义的注释，它们分别是：<code><span style="font-family: Courier; font-size: x-small">@Repository</span></code>、<code><span style="font-family: Courier; font-size: x-small">@Service</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">@Controller</span></code>。在目前的 Spring 版本中，这 3 个注释和 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 是等效的，但是从注释类的命名上，很容易看出这 3 个注释分别和持久层、业务层和控制层（Web 层）相对应。虽然目前这 3 个注释和 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 相比没有什么新意，但 Spring 将在以后的版本中为它们添加特殊的功能。所以，如果 Web 应用程序采用了经典的三层分层结构的话，最好在持久层、业务层和控制层分别采用 <code><span style="font-family: Courier; font-size: x-small">@Repository</span></code>、<code><span style="font-family: Courier; font-size: x-small">@Service</span></code> 和 <code><span style="font-family: Courier; font-size: x-small">@Controller</span></code> 对分层中的类进行注释，而用 <code><span style="font-family: Courier; font-size: x-small">@Component</span></code> 对那些比较中立的类进行注释。</p>
<p><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td><img class="magplus" title="点击查看原始大小图片" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="700" height="0" /><br />
            <img border="0" alt="" src="http://www.ibm.com/i/c.gif" width="8" height="6" /> </td>
        </tr>
    </tbody>
</table>
<table class="no-print" border="0" cellspacing="0" cellpadding="0" align="right">
    <tbody>
        <tr align="right">
            <td><img alt="" src="http://www.ibm.com/i/c.gif" width="100%" height="4" /><br />
            <table border="0" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td valign="middle"><img border="0" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" height="16" /><br />
                        </td>
                        <td valign="top" align="right"><a class="fbox" href="http://topmanopensource.javaeye.com/admin/blogs/#main"><strong><span style="color: #996699">回页首</span></strong></a></td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
<br />
<p><a name="N10409"><span class="atitle"><strong><span style="font-size: large">注释配置和 XML 配置的适用场合</span></strong></span></a></p>
<p>是否有了这些 IOC 注释，我们就可以完全摒除原来 XML 配置的方式呢？答案是否定的。有以下几点原因：</p>
<ul>
    <li>注释配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的，（如 Service 使用了哪几个 DAO 类），这种配置信息不会在部署时发生调整，那么注释配置优于 XML 配置；反之如果这种依赖关系会在部署时发生调整，XML 配置显然又优于注释配置，因为注释是对 Java 源代码的调整，您需要重新改写源代码并重新编译才可以实施调整。 </li>
    <li>如果 Bean 不是自己编写的类（如 <code><span style="font-family: Courier; font-size: x-small">JdbcTemplate</span></code>、<code><span style="font-family: Courier; font-size: x-small">SessionFactoryBean</span></code> 等），注释配置将无法实施，此时 XML 配置是唯一可用的方式。 </li>
    <li>注释配置往往是类级别的，而 XML 配置则可以表现得更加灵活。比如相比于 <code><span style="font-family: Courier; font-size: x-small">@Transaction</span></code> 事务注释，使用 aop/tx 命名空间的事务配置更加灵活和简单。 </li>
</ul>
<p>所以在实现应用中，我们往往需要同时使用注释配置和 XML 配置，对于类级别且不会发生变动的配置可以优先考虑注释配置；而对于那些第三方类以及容易发生调整的配置则应优先考虑使用 XML 配置。Spring 会在具体实施 Bean 创建和 Bean 注入之前将这两种配置方式的元信息融合在一起。</p>
<p><br />
</p>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
    <tbody>
        <tr>
            <td><img class="magplus" title="点击查看原始大小图片" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="700" height="0" /><br />
            <img border="0" alt="" src="http://www.ibm.com/i/c.gif" width="8" height="6" /> </td>
        </tr>
    </tbody>
</table>
<table class="no-print" border="0" cellspacing="0" cellpadding="0" align="right">
    <tbody>
        <tr align="right">
            <td><img alt="" src="http://www.ibm.com/i/c.gif" width="100%" height="4" /><br />
            <table border="0" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td valign="middle"><img border="0" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" height="16" /><br />
                        </td>
                        <td valign="top" align="right"><a class="fbox" href="http://topmanopensource.javaeye.com/admin/blogs/#main"><strong><span style="color: #996699">回页首</span></strong></a></td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
<br />
<p><a name="N1042C"><span class="atitle"><strong><span style="font-size: large">小结</span></strong></span></a></p>
<p>Spring 在 2.1 以后对注释配置提供了强力的支持，注释配置功能成为 Spring 2.5 的最大的亮点之一。合理地使用 Spring 2.5 的注释配置，可以有效减少配置的工作量，提高程序的内聚性。但是这并不意味着传统 XML 配置将走向消亡，在第三方类 Bean 的配置，以及那些诸如数据源、缓存池、持久层操作模板类、事务管理等内容的配置上，XML 配置依然拥有不可替代的地位。</p>
</div>
<img src ="http://www.blogjava.net/EricGu/aggbug/340791.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2010-12-15 14:40 <a href="http://www.blogjava.net/EricGu/archive/2010/12/15/340791.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Spring控制反转的通俗解释【转】</title><link>http://www.blogjava.net/EricGu/archive/2010/12/15/340757.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Wed, 15 Dec 2010 03:39:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2010/12/15/340757.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/340757.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2010/12/15/340757.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/340757.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/340757.html</trackback:ping><description><![CDATA[<div id="blog_text" class="cnt">
<p><font size="2" face="宋体">什么叫控制反转呢？套用好莱坞的一句名言就是：你呆着别动，到时我会找你。 <br />
什么意思呢？就好比一个皇帝和太监 <br />
</font><font size="2"><font face="宋体"><font color="#3366ff">有一天皇帝想宠幸某个美女，于是跟太监说，今夜我要宠幸美女 <br />
皇帝往往不会告诉太监，今晚几点会回宫，会回哪张龙床，他只会告诉太监他要哪位美女</font> <br />
</font></font><font size="2"><font face="宋体"><font color="#ff6600">其它一切都交由太监去安排，到了晚上皇帝回宫时，自然会有美女出现在皇帝的龙床上 <br />
这就是控制反转，而把美女送到皇帝的寝宫里面去就是注射</font> <br />
<font color="#ff0000">太监就是是框架里面的注射控制器类</font>BeanFactory，负责找到美女并送到龙床上去 <br />
<font color="#ff0000">整个后宫可以看成是Spring框架</font>，美女就是Spring控制下的JavaBean <br />
</font></font><font color="#339966" size="2" face="宋体">而传统的模式就是一个饥渴男去找小姐出台 <br />
</font><font size="2"><font face="宋体"><font color="#3366ff">找领班，帮助给介绍一个云云，于是领班就开始给他张罗<br />
介绍一个合适的给他，完事后，再把小姐还给领班，下次再来</font> <br />
</font></font><font size="2"><font face="宋体"><font color="#ff6600">这个过程中，领班就是查询上下文Context，领班的一个职能就是给客户找到他们所要的小姐 <br />
这就是lookup()方法，领班手中的小姐名录就是JNDI//Java Naming and Directory Interface <br />
</font><font color="#ff0000">小姐就是EJB</font>，<font color="#0000ff">饥渴男是客户端</font>，<font color="#ff0000">青楼是EJB容器</font> <br />
看到区别了么？</font></font></p>
<p><font size="2"><font color="#993366" face="宋体">饥渴男去找小姐出台很麻烦，不仅得找，用完后还得把小姐给还回去</font></font></p>
<p><font color="#ff00ff"><font face="宋体"><font size="2">而皇帝爽翻了，什么都不用管，交给太监去处理，控制权转移到太监手中去了</font><font size="2">而不是皇帝，</font></font></font></p>
<p><font color="#ff00ff"><font size="2" face="宋体">必要时候由太监给注射进去就可以了</font></font></p>
</div>
<br />
<img src ="http://www.blogjava.net/EricGu/aggbug/340757.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2010-12-15 11:39 <a href="http://www.blogjava.net/EricGu/archive/2010/12/15/340757.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>[hibernate]注解的说明</title><link>http://www.blogjava.net/EricGu/archive/2010/12/14/340650.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Tue, 14 Dec 2010 07:31:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2010/12/14/340650.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/340650.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2010/12/14/340650.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/340650.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/340650.html</trackback:ping><description><![CDATA[/**<br />
&nbsp;* <br />
&nbsp;* @author liuguangyi<br />
&nbsp;* @content&nbsp; ejb3注解的API定义在javax.persistence.*包里面。<br />
&nbsp;* <br />
&nbsp;* 注释说明：<br />
&nbsp;* @Entity —— 将一个类声明为一个实体bean(即一个持久化POJO类)<br />
&nbsp;* @Id —— 注解声明了该实体bean的标识属性（对应表中的主键）。<br />
&nbsp;* @Table —— 注解声明了该实体bean映射指定的表（table）,目录（catalog）和schema的名字<br />
&nbsp;* @Column —— 注解声明了属性到列的映射。该注解有如下的属性<br />
&nbsp;* &nbsp;name &nbsp;可选，列名（默认值是属性名）<br />
&nbsp;* &nbsp;unique&nbsp;可选，是否在该列上设置唯一约束（默认值false）<br />
&nbsp;* &nbsp;nullable 可选，是否设置该列的值可以为空（默认值false）<br />
&nbsp;*&nbsp; insertable 可选，该列是否作为生成的insert语句中的一个列（默认值true）<br />
&nbsp;*&nbsp; updatable 可选，该列是否作为生成的update语句中的一个列（默认值true）<br />
&nbsp;*&nbsp; columnDefinition 可选，为这个特定列覆盖sql ddl片段（这可能导致无法在不同数据库间移植）<br />
&nbsp;*&nbsp; table&nbsp;可选，定义对应的表（默认为主表）<br />
&nbsp;*&nbsp; length&nbsp;可选，列长度（默认值255）<br />
&nbsp;*&nbsp; precision 可选，列十进制精度（decimal precision)(默认值0）<br />
&nbsp;*&nbsp; scale&nbsp;可选，如果列十进制数值范围（decimal scale）可用，在此设置（默认值0）<br />
&nbsp;* @GeneratedValue —— 注解声明了主键的生成策略。该注解有如下属性<br />
&nbsp;* &nbsp;strategy 指定生成的策略（JPA定义的），这是一个GenerationType。默认是GenerationType.&nbsp;AUTO<br />
&nbsp;* &nbsp;&nbsp;GenerationType.AUTO 主键由程序控制<br />
&nbsp;*&nbsp; &nbsp;GenerationType.TABLE 使用一个特定的数据库表格来保存主键<br />
&nbsp;*&nbsp; &nbsp;GenerationType.IDENTITY 主键由数据库自动生成（主要是自动增长类型）<br />
&nbsp;*&nbsp; &nbsp;GenerationType.SEQUENCE 根据底层数据库的序列来生成主键，条件是数据库支持序列。（这个值要与generator一起使用）<br />
&nbsp;*&nbsp; generator 指定生成主键使用的生成器（可能是orcale中的序列）。<br />
&nbsp;* @SequenceGenerator —— 注解声明了一个数据库序列。该注解有如下属性<br />
&nbsp;* &nbsp;name&nbsp;表示该表主键生成策略名称，它被引用在@GeneratedValue中设置的&#8220;gernerator&#8221;值中<br />
&nbsp;* &nbsp;sequenceName 表示生成策略用到的数据库序列名称。<br />
&nbsp;* &nbsp;initialValue 表示主键初始值，默认为0.<br />
&nbsp;* &nbsp;allocationSize 每次主键值增加的大小，例如设置成1，则表示每次创建新记录后自动加1，默认为50.<br />
&nbsp;* @GenericGenerator —— 注解声明了一个hibernate的主键生成策略。支持十三种策略。该注解有如下属性<br />
&nbsp;* &nbsp;name 指定生成器名称<br />
&nbsp;* &nbsp;strategy 指定具体生成器的类名（指定生成策略）。<br />
&nbsp;* &nbsp;parameters 得到strategy指定的具体生成器所用到的参数。<br />
&nbsp;* &nbsp;&nbsp; 其十三种策略（strategy属性的值）如下：<br />
&nbsp;* &nbsp;&nbsp;1.native 对于orcale采用Sequence方式，对于MySQL和SQL Server采用identity(处境主键生成机制)，<br />
&nbsp;* &nbsp;&nbsp;&nbsp; native就是将主键的生成工作将由数据库完成，hibernate不管（很常用）<br />
&nbsp;* &nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "native")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2.uuid 采用128位的uuid算法生成主键，uuid被编码为一个32位16进制数字的字符串。占用空间大（字符串类型）。<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.hilo 要在数据库中建立一张额外的表，默认表名为hibernate_unque_key，默认字段为integer类型，名称是next_hi（比较少用）<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "hilo")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.assigned 在插入数据的时候主键由程序处理（很常用），这是&lt;generator&gt;元素没有指定时的默认生成策略。等同于JPA中的AUTO。<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "assigned")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 5.identity 使用SQL Server和MySQL的自增字段，这个方法不能放到Oracle中，Oracle不支持自增字段，要设定sequence(MySQL和SQL Server中很常用)。等同于JPA中的IDENTITY<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "identity")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 6.select 使用触发器生成主键（主要用于早期的数据库主键生成机制，少用）<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "select")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 7.sequence 调用谨慎数据库的序列来生成主键，要设定序列名，不然hibernate无法找到。<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;@GenericGenerator(name = "paymentableGenerator", strategy = "sequence",&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })<br />
&nbsp;*&nbsp;&nbsp;8.seqhilo 通过hilo算法实现，但是主键历史保存在Sequence中，适用于支持Sequence的数据库，如Orcale(比较少用） <br />
&nbsp;*&nbsp;&nbsp;例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "seqhilo",&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; parameters = { @Parameter(name = "max_lo", value = "5") })<br />
&nbsp;*&nbsp;&nbsp;9.increnment 插入数据的时候hibernate会给主键添加一个自增的主键，但是一个hibernate实例就维护一个计数器，所以在多个实例运行的时候不能使用这个方法。<br />
&nbsp;*&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "increnment")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 10.foreign 使用另一个相关的对象的主键。通常和&lt;on<wbr>e-to-on<wbr>e&gt;联合起来使用。<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@Id&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; @GeneratedValue(generator = "idGenerator")&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "idGenerator", strategy = "foreign",&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; parameters = { @Parameter(name = "property", value = "info") })&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; Integer id;<br />
&nbsp;*&nbsp; &nbsp;@On<wbr>eToOne&nbsp; <br />
&nbsp;*&nbsp; &nbsp;EmployeeInfo info;<br />
&nbsp;*&nbsp;&nbsp;11.guid 采用数据库底层的guid算法机制，对应MySQL的uuid()函数，SQL Server的newid()函数，ORCALE的rawtohex(sys_guid())函数等<br />
&nbsp;*&nbsp;&nbsp;例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "guid") <br />
&nbsp;*&nbsp;&nbsp;12.uuid.hex 看uudi,建议用uuid替换<br />
&nbsp;*&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; @GenericGenerator(name = "paymentableGenerator", strategy = "uuid.hex")<br />
&nbsp;*&nbsp;&nbsp;13.sequence-identity sequence策略的扩展，采用立即检索策略来获取sequence值，需要JDBC3.0和JDK4以上（含1.4）版本<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 例：@GeneratedValue(generator = "paymentableGenerator")&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;@GenericGenerator(name = "paymentableGenerator", strategy = "sequence-identity",&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;@On<wbr>eToOne 设置一对一个关联。cascade属性有五个值(只有CascadeType.ALL好用？很奇怪)，分别是CascadeType.PERSIST(级联新建)，CascadeType.REMOVE（级联删除），CascadeType.REFRESH（级联刷新），CascadeType.MERGE（级联更新），CascadeType.ALL（全部四项）<br />
&nbsp;*&nbsp;&nbsp;&nbsp; 方法一<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &nbsp;主表： ?@On<wbr>eToOne(cascade = CascadeType.ALL)<br />
&nbsp;*&nbsp;&nbsp; &nbsp;&nbsp; @PrimaryKeyJoinColumn<br />
&nbsp;*&nbsp;&nbsp; &nbsp;&nbsp; public 从表类 get从表类(){return 从表对象}<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 从表：没有主表类。<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 注意：这种方法要求主表与从表的主键值想对应。<br />
&nbsp;*&nbsp;&nbsp; 方法二<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 主表：?@On<wbr>eToOne(cascade = CascadeType.ALL)<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @JoinColumn(name="主表外键") //这里指定的是数据库中的外键字段。<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public 从表类 get从表类(){return 从表类}<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 从表：@On<wbr>eToOne(mappedBy = "主表类中的从表属性")//例主表User中有一个从表属性是Heart类型的heart，这里就填heart<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public 主表类 get主表类(){return 主表对象}<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 注意：@JoinColumn是可选的。默认值是从表变量名+"_"+从表的主键（注意，这里加的是主键。而不是主键对应的变量）。<br />
&nbsp;*&nbsp;方法三<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 主表：@On<wbr>eToOne(cascade=CascadeType.ALL)<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @JoinTable( name="关联表名",<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;joinColumns = @JoinColumn(name="主表外键"),<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;inverseJoinColumns = @JoinColumns(name="从表外键")<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 从表：@On<wbr>eToOne(mappedBy = "主表类中的从表属性")//例主表User中有一个从表属性是Heart类型的heart，这里就填heart<br />
&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public 主表类 get主表类(){return 主表对象}&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp; @ManyToOne 设置多对一关联<br />
&nbsp;*&nbsp;&nbsp;&nbsp; 方法一&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; @ManyToOne(cascade={CasCadeType.PERSIST,CascadeType.MERGE})<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @JoinColumn(name="外键")<br />
&nbsp;*&nbsp;&nbsp;&nbsp; public 主表类 get主表类(){return 主表对象}<br />
&nbsp;*&nbsp;&nbsp;&nbsp; 方法二<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE})<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @JoinTable(name="关联表名"，<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &nbsp;joinColumns = @JoinColumn(name="主表外键"),<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &nbsp;inverseJoinColumns = @JoinColumns(name="从表外键")<br />
&nbsp;*&nbsp;&nbsp;&nbsp; )<br />
&nbsp;*&nbsp; @On<wbr>eToMany 设置一对多关联。cascade属性指定关联级别,参考@On<wbr>eToOne中的说明。fetch指定是否延迟加载，值为FetchType.LAZY表示延迟，为FetchType.EAGER表示立即加载<br />
&nbsp;*&nbsp;&nbsp;&nbsp; 方法一&nbsp;&nbsp;&nbsp;&nbsp; 使用这种配置，在为&#8220;一端&#8221;添加&#8220;多端&#8221;时，不会修改&#8220;多端&#8221;的外键。在&#8220;一端&#8221;加载时，不会得到&#8220;多端&#8221;。如果使用延迟加载，在读&#8220;多端&#8221;列表时会出异常，立即加载在得到多端时，是一个空集合（集合元素为0）。<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &#8220;一端&#8221;配置<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @On<wbr>eToMany(mappedBy="&#8220;多端&#8221;的属性")<br />
&nbsp;*&nbsp;&nbsp;&nbsp; public List&lt;&#8220;多端&#8221;类&gt; get&#8220;多端&#8221;列表(){return &#8220;多端&#8221;列表}<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &#8220;多端&#8221;配置参考@ManyToOne.&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; 方法二<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &#8220;一端&#8221;配置<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @On<wbr>eToMany(mappedBy="&#8220;多端&#8221;的属性")<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @MapKey(name="&#8220;多端&#8221;做为Key的属性")<br />
&nbsp;*&nbsp;&nbsp;&nbsp; public Map&lt;&#8220;多端&#8221;做为Key的属性的类,主表类&gt; get&#8220;多端&#8221;列表（）{return &#8220;多端&#8221;列表}<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &#8220;多端&#8221;配置参考@ManyToOne. <br />
&nbsp;*&nbsp;&nbsp;&nbsp; 方法三 使用这种配置，在为&#8220;一端&#8221;添加&#8220;多端&#8221;时，可以修改&#8220;多端&#8221;的外键。<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &#8220;一端&#8221;配置<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @On<wbr>eToMany<br />
&nbsp;*&nbsp;&nbsp;&nbsp; @JoinColumn(name="&#8220;多端&#8221;外键") <br />
&nbsp;*&nbsp;&nbsp;&nbsp; public List&lt;&#8220;多端&#8221;类&gt; get&#8220;多端&#8221;列表(){return &#8220;多端&#8221;列表}<br />
&nbsp;*&nbsp;&nbsp;&nbsp; &#8220;多端&#8221;配置参考@ManyToOne.&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp;&nbsp; <br />
&nbsp;*&nbsp;&nbsp; <br />
&nbsp;*/
<img src ="http://www.blogjava.net/EricGu/aggbug/340650.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2010-12-14 15:31 <a href="http://www.blogjava.net/EricGu/archive/2010/12/14/340650.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java语法总结 - 方法</title><link>http://www.blogjava.net/EricGu/archive/2009/06/30/284798.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Tue, 30 Jun 2009 09:17:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2009/06/30/284798.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/284798.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2009/06/30/284798.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/284798.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/284798.html</trackback:ping><description><![CDATA[一、方法的重写。<br />
<br />
1、重写只能出现在继承关系之中。当一个类继承它的父类方法时，都有机会重写该父类的方法。一个特例是父类的方法被标识为final。重写的主要优点是能够定义某个子类型特有的行为。<br />
&nbsp;&nbsp; &nbsp;class Animal {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Animal is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;class Horse extends Animal{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
2、对于从父类继承来的抽象方法，要么在子类用重写的方式设计该方法，要么把子类也标识为抽象的。所以抽象方法可以说是必须要被重写的方法。<br />
<br />
3、重写的意义。<br />
重写方法可以实现多态，用父类的引用来操纵子类对象，但是在实际运行中对象将运行其自己特有的方法。<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main (String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Animal h = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;h.eat();&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
&nbsp;&nbsp; &nbsp;class Animal {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Animal is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;class Horse extends Animal{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void buck(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
一个原则是：使用了什么引用，编译器就会只调用引用类所拥有的方法。如果调用子类特有的方法，如上例的h.buck(); 编译器会抱怨的。也就是说，编译器只看引用类型，而不是对象类型。<br />
<br />
4、重写方法的规则。<br />
若想实现一个合格重写方法，而不是重载，那么必须同时满足下面的要求！<br />
<br />
A、重写规则之一：重写方法不能比被重写方法限制有更严格的访问级别。<br />
（但是可以更广泛，比如父类方法是包访问权限，子类的重写方法是public访问权限。）<br />
比如：Object类有个toString()方法，开始重写这个方法的时候我们总容易忘记public修饰符，编译器当然不会放过任何教训我们的机会。出错的原因就是：没有加任何访问修饰符的方法具有包访问权限，包访问权限比public当然要严格了，所以编译器会报错的。<br />
<br />
B、重写规则之二：参数列表必须与被重写方法的相同。<br />
重写有个孪生的弟弟叫重载，也就是后面要出场的。如果子类方法的参数与父类对应的方法不同，那么就是你认错人了，那是重载，不是重写。<br />
<br />
C、重写规则之三：返回类型必须与被重写方法的返回类型相同。<br />
父类方法A：void eat(){}&nbsp; 子类方法B：int eat(){}&nbsp; 两者虽然参数相同，可是返回类型不同，所以不是重写。<br />
父类方法A：int eat(){}&nbsp;&nbsp; 子类方法B：long eat(){}&nbsp; 返回类型虽然兼容父类，但是不同就是不同，所以不是重写。<br />
<br />
D、重写规则之四：重写方法不能抛出新的异常或者比被重写方法声明的检查异常更广的检查异常。但是可以抛出更少，更有限或者不抛出异常。<br />
&nbsp;&nbsp; &nbsp;import java.io.*;<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main (String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Animal h = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;try {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;h.eat();&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;catch (Exception e) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
&nbsp;&nbsp; &nbsp;class Animal {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat() throws Exception{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Animal is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;throw new Exception();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;class Horse extends Animal{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat() throws IOException{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;throw new IOException();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
这个例子中，父类抛出了检查异常Exception，子类抛出的IOException是Exception的子类，也即是比被重写的方法抛出了更有限的异常，这是可以的。如果反过来，父类抛出IOException，子类抛出更为宽泛的Exception，那么不会通过编译的。<br />
注意：这种限制只是针对检查异常，至于运行时异常RuntimeException及其子类不再这个限制之中。<br />
<br />
E、重写规则之五：不能重写被标识为final的方法。<br />
<br />
F、重写规则之六：如果一个方法不能被继承，则不能重写它。<br />
比较典型的就是父类的private方法。下例会产生一个有趣的现象。<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main (String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//Animal h = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Horse h = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;h.eat();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
&nbsp;&nbsp; &nbsp;class Animal {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;private void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Animal is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;class Horse extends Animal{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is eating.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
这段代码是能通过编译的。表面上看来违反了第六条规则，但实际上那是一点巧合。Animal类的eat()方法不能被继承，因此Horse类中的eat()方法是一个全新的方法，不是重写也不是重载，只是一个只属于Horse类的全新的方法！这点让很多人迷惑了，但是也不是那么难以理解。<br />
main()方法如果是这样：<br />
&nbsp;&nbsp; &nbsp;Animal h = new Horse();<br />
&nbsp;&nbsp; &nbsp;//Horse h = new Horse();<br />
&nbsp;&nbsp; &nbsp;h.eat();<br />
编译器会报错，为什么呢？Horse类的eat()方法是public的啊！应该可以调用啊！请牢记，多态只看父类引用的方法，而不看子类对象的方法！<br />
<br />
<br />
二、方法的重载。<br />
重载是有好的，它不要求你在调用一个方法之前转换数据类型，它会自动地寻找匹配的方法。方法的重载是在编译时刻就决定调用哪个方法了，和重写不同。最最常用的地方就是构造器的重载。<br />
<br />
1、基本数据类型参数的重载。<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(byte b){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("method:byte");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(short s){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("method:short");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(int i){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("method:int");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(float f){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("method:float");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(double d){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("method:double");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main (String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method((byte)1);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method('c');<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(1);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(1L);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(1.1);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(1.1f);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
输出结果：<br />
method:byte<br />
method:int<br />
method:int<br />
method:float<br />
method:double<br />
method:float<br />
<br />
可以看出：首先要寻找的是数据类型正好匹配方法。如果找不到，那么就提升为表达能力更强的数据类型，如上例没有正好容纳long的整数类型，那么就转换为float类型的。如果通过提升也不能找到合适的兼容类型，那么编译器就会报错。反正是不会自动转换为较小的数据类型的，必须自己强制转换，自己来承担转变后果。<br />
<br />
char类型比较特殊，如果找不到正好匹配的类型，它会转化为int而不是short，虽然char是16位的。<br />
<br />
<br />
2、重载方法的规则。<br />
<br />
A、被重载的方法必须改变参数列表。<br />
参数必须不同，这是最重要的！不同有两个方面，参数的个数，参数的类型，参数的顺序。<br />
<br />
B、被重载的方法与返回类型无关。<br />
也就是说，不能通过返回类型来区分重载方法。<br />
<br />
C、被重载的方法可以改变访问修饰符。<br />
没有重写方法那样严格的限制。<br />
<br />
D、被重载的方法可以声明新的或者更广的检查异常。<br />
没有重写方法那样严格的限制。<br />
<br />
E、方法能够在一个类中或者在一个子类中被重载。<br />
<br />
<br />
3、带对象引用参数的方法重载。<br />
&nbsp;&nbsp; &nbsp;class Animal {}<br />
&nbsp;&nbsp; &nbsp;class Horse extends Animal{}<br />
&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(Animal a){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Animal is called.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static void method(Horse h){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is called.");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main (String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Animal a = new Animal();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Horse h = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Animal ah = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(a);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(h);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;method(ah);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp; &nbsp;}<br />
输出结果是：<br />
Animal is called.<br />
Horse is called.<br />
Animal is called.<br />
前两个输出没有任何问题。第三个方法为什么不是输出&#8220;Horse is called.&#8221;呢？还是那句老话，要看引用类型而不是对象类型，方法重载是在编译时刻就决定的了，引用类型决定了调用哪个版本的重载方法。<br />
<br />
<br />
4、重载和重写方法区别的小结。<br />
如果能彻底弄明白下面的例子，说明你对重载和重写非常了解了，可以结束这节的复习了。<br />
&nbsp;&nbsp; &nbsp;class Animal {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Animal is eating.");&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;class Horse extends Animal{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is eating.");&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public void eat(String food){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.println ("Horse is eating " + food);<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main (String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Animal a = new Animal();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Horse h = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;Animal ah = new Horse();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;a.eat();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;h.eat();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;h.eat("apple");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;ah.eat();<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//a.eat("apple");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//ah.eat("apple");<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
四个输出分别是什么？被注释的两条语句为什么不能通过编译？<br />
第一条：a.eat(); 普通的方法调用，没有多态，没什么技术含量。调用了Animal类的eat()方法，输出：Animal is eating.<br />
第二条：h.eat(); 普通的方法调用，也没什么技术含量。调用了Horse类的eat()方法，输出：Horse is eating.<br />
第三条：h.eat("apple"); 重载。Horse类的两个eat()方法重载。调用了Horse类的eat(String food)方法，输出：Horse is eating apple<br />
第四条：ah.eat(); 多态。前面有例子了，不难理解。输出：Horse is eating.<br />
第五条：a.eat("apple"); 低级的错误，Animal类中没有eat(String food)方法。因此不能通过编译。<br />
第六条：ah.eat("apple"); 关键点就在这里。解决的方法还是那句老话，不能看对象类型，要看引用类型。Animal类中没有eat(String food)方法。因此不能通过编译。<br />
<br />
小结一下：多态不决定调用哪个重载版本；多态只有在决定哪个重写版本时才起作用。<br />
重载对应编译时，重写对应运行时。够简洁的了吧！<br />
<br />
<br />
三、构造方法。<br />
构造方法是一种特殊的方法，没有构造方法就不能创建一个新对象。实际上，不仅要调用对象实际类型的构造方法，还要调用其父类的构造方法，向上追溯，直到Object类。构造方法不必显式地调用，当使用new关键字时，相应的构造方法会自动被调用。<br />
<br />
1、构造方法的规则。<br />
A、构造方法能使用任何访问修饰符。包括private，事实上java类库有很多都是这样的，设计者不希望使用者创建该类的对象。<br />
<br />
B、构造方法的名称必须与类名相同。这样使得构造方法与众不同，如果我们遵守sun的编码规范，似乎只有构造方法的首字母是大写的。<br />
<br />
C、构造方法不能有返回类型。<br />
反过来说，有返回类型的不是构造方法<br />
&nbsp;&nbsp; &nbsp;public class Test {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;int Test(){<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return 1;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
这个方法是什么东西？一个冒充李逵的李鬼而已，int Test()和其他任何普通方法没什么两样，就是普通的方法！只不过看起来很恶心，类似恶心的东西在考试卷子里比较多。<br />
<br />
D、如果不在类中创建自己的构造方法，编译器会自动生成默认的不带参数的构造函数。<br />
这点很容易验证！写一个这样简单的类，编译。<br />
class Test {<br />
}<br />
对生成的Test.class文件反编译：javap Test，可以看到：<br />
D:"JavaCode"bin&gt;javap Test<br />
Compiled from "Test.java"<br />
class Test extends java.lang.Object{<br />
&nbsp;&nbsp;&nbsp; Test();<br />
}<br />
看到编译器自动添加的默认构造函数了吧！<br />
<br />
E、如果只创建了带参数的构造方法，那么编译器不会自动添加无参的构造方法的！<br />
<br />
F、在每个构造方法中，如果使用了重载构造函数this()方法，或者父类的构造方法super()方法，那么this()方法或者super()方法必须放在第一行。而且这两个方法只能选择一个，因此它们之间没有顺序问题。<br />
<br />
G、除了编译器生成的构造方法，而且没有显式地调用super()方法，那么编译器会插入一个super()无参调用。<br />
<br />
H、抽象类有构造方法。<br />
<br />
<br />
四、静态方法的重载与重写（覆盖）。<br />
<br />
1、静态方法是不能被覆盖的。可以分两种情况讨论：<br />
<br />
A、子类的非静态方法&#8220;覆盖&#8221;父类的静态方法。<br />
这种情况下，是不能通过编译的。<br />
<br />
<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%; padding-top: 4px; border-bottom: #cccccc 1px solid; background-color: #eeeeee"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff">class</span><span style="color: #000000">&nbsp;Father{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff">static</span><span style="color: #000000">&nbsp;</span><span style="color: #0000ff">void</span><span style="color: #000000">&nbsp;print(){<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println&nbsp;(</span><span style="color: #000000">"</span><span style="color: #000000">in&nbsp;father&nbsp;&nbsp;method</span><span style="color: #000000">"</span><span style="color: #000000">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
</span><span style="color: #0000ff">class</span><span style="color: #000000">&nbsp;Child&nbsp;</span><span style="color: #0000ff">extends</span><span style="color: #000000">&nbsp;Father{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff">void</span><span style="color: #000000">&nbsp;print(){<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println&nbsp;(</span><span style="color: #000000">"</span><span style="color: #000000">in&nbsp;child&nbsp;method</span><span style="color: #000000">"</span><span style="color: #000000">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}</span></div>
<br />
static方法表示该方法不关联具体的类的对象，可以通过类名直接调用，也就是编译的前期就绑定了，不存在后期动态绑定，也就是不能实现多态。子类的非静态方法是与具体的对象绑定的，两者有着不同的含义。<br />
<br />
B、子类的静态方法&#8220;覆盖&#8221;父类静态方法。<br />
这个覆盖依然是带引号的。事实上把上面那个例子Child类的print方法前面加上static修饰符，确实能通过编译！但是不要以为这就是多态！多态的特点是动态绑定，看下面的例子：<br />
<br />
<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%; padding-top: 4px; border-bottom: #cccccc 1px solid; background-color: #eeeeee"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff">class</span><span style="color: #000000">&nbsp;Father{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff">static</span><span style="color: #000000">&nbsp;</span><span style="color: #0000ff">void</span><span style="color: #000000">&nbsp;print(){<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println&nbsp;(</span><span style="color: #000000">"</span><span style="color: #000000">in&nbsp;father&nbsp;&nbsp;method</span><span style="color: #000000">"</span><span style="color: #000000">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
</span><span style="color: #0000ff">class</span><span style="color: #000000">&nbsp;Child&nbsp;</span><span style="color: #0000ff">extends</span><span style="color: #000000">&nbsp;Father{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff">static</span><span style="color: #000000">&nbsp;</span><span style="color: #0000ff">void</span><span style="color: #000000">&nbsp;print(){<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println&nbsp;(</span><span style="color: #000000">"</span><span style="color: #000000">in&nbsp;child&nbsp;method</span><span style="color: #000000">"</span><span style="color: #000000">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
<br />
</span><span style="color: #0000ff">class</span><span style="color: #000000">&nbsp;Test{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff">public</span><span style="color: #000000">&nbsp;</span><span style="color: #0000ff">static</span><span style="color: #000000">&nbsp;</span><span style="color: #0000ff">void</span><span style="color: #000000">&nbsp;main&nbsp;(String[]&nbsp;args)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Father&nbsp;f&nbsp;</span><span style="color: #000000">=</span><span style="color: #0000ff">new</span><span style="color: #000000">&nbsp;Child();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f.print();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}</span></div>
<br />
输出结果是：in father&nbsp; method<br />
从这个结果可以看出，并没有实现多态。<br />
但是这种形式很迷惑人，貌似多态，实际编程中千万不要这样搞，会把大家搞懵的！<br />
它不符合覆盖表现出来的特性，不应该算是覆盖！<br />
总而言之，静态方法不能被覆盖。<br />
<br />
2、静态方法可以和非静态方法一样被重载。<br />
这样的例子太多了，我不想写例程了。看看java类库中很多这样的例子。<br />
如java.util.Arrays类的一堆重载的binarySearch方法。<br />
在这里提一下是因为查资料时看到这样的话&#8220;sun的SL275课程说，静态方法只能控制静态变量（他们本身没有），静态方法不能被重载和覆盖&#8230;&#8230;&#8221; <br />
大家不要相信啊！可以重载的。而且静态与非静态方法可以重载。<br />
<br />
从重载的机制很容易就理解了，重载是在编译时刻就决定的了，非静态方法都可以，静态方法怎么可能不会呢？<br />
<img src ="http://www.blogjava.net/EricGu/aggbug/284798.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2009-06-30 17:17 <a href="http://www.blogjava.net/EricGu/archive/2009/06/30/284798.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java语法总结 - 字符串</title><link>http://www.blogjava.net/EricGu/archive/2009/06/30/284780.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Tue, 30 Jun 2009 07:34:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2009/06/30/284780.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/284780.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2009/06/30/284780.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/284780.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/284780.html</trackback:ping><description><![CDATA[Java的String太特别了，也太常用了，所以重要。我初学Java就被它搞蒙了，太多混淆的概念了，比如它的不变性。所以必须深入机制地去理解它。<br />
<br />
<br />
1、String中的每个字符都是一个16位的Unicode字符，用Unicode很容易表达丰富的国际化字符集，比如很好的中文支持。甚至Java的标识符都可以用汉字，但是没人会用吧（只在一本清华的《Java2实用教程》看过）。<br />
<br />
2、判断空字符串。根据需要自己选择某个或者它们的组合<br />
&nbsp;&nbsp; &nbsp;if ( s == null )&nbsp;&nbsp; &nbsp;//从引用的角度<br />
&nbsp;&nbsp; &nbsp;if ( s.length() == 0 ) &nbsp;&nbsp; &nbsp;//从长度判别<br />
&nbsp;&nbsp; &nbsp;if ( s.trim().length () == 0 ) &nbsp;&nbsp; &nbsp;//是否有多个空白字符<br />
trim()方法的作用是是移除前导和尾部的Unicode值小于'"u0020'的字符，并返回&#8220;修剪&#8221;好的字符串。这种方法很常用，比如需要用户输入用户名，用户不小心加了前导或者尾部空格，一个好的程序应该知道用户不是故意的，即使是故意的也应该智能点地处理。<br />
判断空串是很常用的操作，但是Java类库直到1.6才提供了isEmpty()方法。当且仅当 length() 为 0 时返回 true。<br />
<br />
3、未初始化、空串""与null。它们是不同的概念。对未初始化的对象操作会被编译器挡在门外；null是一个特殊的初始化值，是一个不指向任何对象的引用，对引用为null的对象操作会在运行时抛出异常NullPointerException；而空串是长度为0的字符串，和别的字符串的唯一区别就是长度为0。<br />
例子：<br />
&nbsp;&nbsp; &nbsp;public class StringTest{<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;static String s1;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;public static void main(String[] args) {<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String s2;<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;String s3 = "";<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.print(s1.isEmpty());&nbsp;&nbsp; &nbsp; //运行时异常<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.print(s2.isEmpty());&nbsp;&nbsp; &nbsp; //编译出错<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;System.out.print(s3.isEmpty());&nbsp;&nbsp; &nbsp; //ok！输出true<br />
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;}<br />
&nbsp;&nbsp; &nbsp;}<br />
<br />
4、String类的方法很多，在编写相关代码的时候看看JDK文档时有好处的，要不然花了大量时间实现一个已经存在的方法是很不值得的，因为编写、测试、维护自己的代码使项目的成本增加，利润减少，严重的话会导致开不出工资&#8230;&#8230;<br />
<br />
5、字符串的比较。<br />
Java不允许自定义操作符重载，因此字符串的比较要用compareTo() 或者 compareToIgnoreCase()。s1.compareTo(s2)，返回值大于0则，则前者大；等于0，一般大；小于0，后者大。比较的依据是字符串中各个字符的Unicode值。<br />
<br />
6、toString()方法。<br />
Java的任何对象都有toString()方法，是从Object对象继承而来的。它的作用就是让对象在输出时看起来更有意义，而不是奇怪的对象的内存地址。对测试也是很有帮助的。<br />
<br />
7、String对象是不变的！可以变化的是String对象的引用。<br />
String name = "ray";<br />
name.concat("long");&nbsp; //字符串连接<br />
System.out.println(name); //输出name，ok，还是"ray"<br />
name = name.concat("long");&nbsp; //把字符串对象连接的结果赋给了name引用<br />
System.out.println(name);&nbsp; //输出name，oh！，变成了"raylong"<br />
上述三条语句其实产生了3个String对象，"ray"，"long"，"raylong"。第2条语句确实产生了"raylong"字符串，但是没有指定把该字符串的引用赋给谁，因此没有改变name引用。第3条语句根据不变性，并没有改变"ray"，JVM创建了一个新的对象，把"ray"，"long"的连接赋给了name引用，因此引用变了，但是原对象没变。<br />
<br />
8、String的不变性的机制显然会在String常量内有大量的冗余。如："1" + "2" + "3" +......+ "n" 产生了n+(n+1)个String对象！因此Java为了更有效地使用内存，JVM留出一块特殊的内存区域，被称为&#8220;String常量池&#8221;。对String多么照顾啊！当编译器遇见String常量的时候，它检查该池内是否已经存在相同的String常量。如果找到，就把新常量的引用指向现有的String，不创建任何新的String常量对象。<br />
<br />
那么就可能出现多个引用指向同一个String常量，会不会有别名的危险呢？No problem！String对象的不变性可以保证不会出现别名问题！这是String对象与普通对象的一点区别。<br />
<br />
乍看起来这是底层的机制，对我们编程没什么影响。而且这种机制会大幅度提高String的效率，实际上却不是这样。为连接n个字符串使用字符串连接操作时，要消耗的时间是n的平方级！因为每两个字符串连接，它们的内容都要被复制。因此在处理大量的字符串连接时，而且要求性能时，我们不要用String，StringBuffer是更好的选择。<br />
<br />
8、StringBuffer类。StringBuffer类是可变的，不会在字符串常量池中，而是在堆中，不会留下一大堆无用的对象。而且它可将字符串缓冲区安全地用于多个线程。每个StringBuffer对象都有一定的容量。只要StringBuffer对象所包含的字符序列的长度没有超出此容量，就无需分配新的内部缓冲区数组。如果内部缓冲区溢出，则此容量自动增大。这个固定的容量是16个字符。我给这种算法起个名字叫&#8220;添饭算法&#8221;。先给你一满碗饭，不够了再给你一满碗饭。<br />
例子：<br />
&nbsp;&nbsp; &nbsp;StringBuffer sb = new StringBuffer();&nbsp;&nbsp; &nbsp;//初始容量为 16 个字符<br />
&nbsp;&nbsp; &nbsp;sb.append("1234");&nbsp;&nbsp; &nbsp;//这是4个字符，那么16个字符的容量就足够了，没有溢出<br />
&nbsp;&nbsp; &nbsp;System.out.println(sb.length());&nbsp;&nbsp; &nbsp;//输出字符串长度是4<br />
&nbsp;&nbsp; &nbsp;System.out.println(sb.capacity());&nbsp;&nbsp; &nbsp;//输出该字符串缓冲区的容量是16<br />
<br />
&nbsp;&nbsp; &nbsp;sb.append("12345678901234567");&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//这是17个字符，16个字符的容量不够了，扩容为17+16个字符的容量<br />
&nbsp;&nbsp; &nbsp;System.out.println(sb.length());&nbsp;&nbsp; &nbsp;//输出字符串长度是17<br />
&nbsp;&nbsp; &nbsp;System.out.println(sb.capacity());&nbsp;&nbsp; &nbsp;//输出该字符串缓冲区的容量是34<br />
<br />
&nbsp;&nbsp; &nbsp;sb.append("890").reverse().insert(10,"-");&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp; &nbsp;System.out.println(sb);&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;//输出0987654321-09876543214321<br />
<br />
字符串的长度和字符缓冲区的容量是两个概念，注意区别。<br />
还有串联的方式看起来是不是很酷！用返回值连接起来可以实现这种简洁和优雅。<br />
<br />
10、StringBuilder类。 从J2SE 5.0 提供了StringBuilder类，它和StringBuffer类是孪生兄弟，很像。它存在的价值在于：对字符串操作的效率更高。不足的是线程安全无法保证，不保证同步。那么两者性能到底差多少呢？很多！<br />
请参阅：http://book.csdn.net/bookfiles/135/1001354628.shtml<br />
实践：<br />
单个线程的时候使用StringBuilder类，以提高效率，而且它的API和StringBuffer兼容，不需要额外的学习成本，物美价廉。多线程时使用StringBuffer，以保证安全。<br />
<br />
11、字符串的比较。<br />
下面这条可能会让你晕，所以你可以选择看或者不看。它不会对你的职业生涯造成任何影响。而且谨记一条，比较字符串要用equals()就ok了！一旦用了&#8220;==&#8221;就会出现很怪异的现象。之所以把这部分放在最后，是想节省大家的时间，因为这条又臭又长。推荐三种人：一、没事闲着型。二、想深入地理解Java的字符串，即使明明知道学了也没用。三、和我一样爱好研究&#8220;茴&#8221;字有几种写法。<br />
<br />
还是那句老话，String太特殊了，以至于某些规则对String不起作用。个人感觉这种特殊性并不好。看例子：<br />
例子A：<br />
&nbsp;&nbsp; &nbsp;String str1 = "java";<br />
&nbsp;&nbsp; &nbsp;String str2 = "java";<br />
&nbsp;&nbsp; &nbsp;System.out.print(str1==str2);<br />
地球上有点Java基础的人都知道会输出false，因为==比较的是引用，equals比较的是内容。不是我忽悠大家，你们可以在自己的机子上运行一下，结果是true！原因很简单，String对象被放进常量池里了，再次出现&#8220;java&#8221;字符串的时候，JVM很兴奋地把str2的引用也指向了&#8220;java&#8221;对象，它认为自己节省了内存开销。不难理解吧 呵呵<br />
例子B：<br />
&nbsp;&nbsp; &nbsp;String str1 = new String("java");<br />
&nbsp;&nbsp; &nbsp;String str2 = new String("java");<br />
&nbsp;&nbsp; &nbsp;System.out.print(str1==str2);<br />
看过上例的都学聪明了，这次肯定会输出true！很不幸，JVM并没有这么做，结果是false。原因很简单，例子A中那种声明的方式确实是在String常量池创建&#8220;java&#8221;对象，但是一旦看到new关键字，JVM会在堆中为String分配空间。两者声明方式貌合神离，这也是我把&#8220;如何创建字符串对象&#8221;放到后面来讲的原因。大家要沉住气，还有一个例子。<br />
例子C：<br />
&nbsp;&nbsp; &nbsp;String str1 = "java";<br />
&nbsp;&nbsp; &nbsp;String str2 = "blog";<br />
&nbsp;&nbsp; &nbsp;String s = str1+str2;<br />
&nbsp;&nbsp; &nbsp;System.out.print(s=="javablog");<br />
再看这个例子，很多同志不敢妄言是true还是false了吧。爱玩脑筋急转弯的人会说是false吧&#8230;&#8230;恭喜你，你会抢答了！把那个&#8220;吧&#8221;字去掉你就完全正确。原因很简单，JVM确实会对型如String str1 = "java"; 的String对象放在字符串常量池里，但是它是在编译时刻那么做的，而String s = str1+str2; 是在运行时刻才能知道（我们当然一眼就看穿了，可是Java必须在运行时才知道的，人脑和电脑的结构不同），也就是说str1+str2是在堆里创建的，s引用当然不可能指向字符串常量池里的对象。没崩溃的人继续看例子D。<br />
例子D：<br />
&nbsp;&nbsp; &nbsp;String s1 = "java";<br />
&nbsp;&nbsp; &nbsp;String s2 = new String("java");<br />
&nbsp;&nbsp; &nbsp;System.out.print(s1.intern()==s2.intern());<br />
intern()是什么东东？反正结果是true。如果没用过这个方法，而且训练有素的程序员会去看JDK文档了。简单点说就是用intern()方法就可以用&#8220;==&#8221;比较字符串的内容了。在我看到intern()方法到底有什么用之前，我认为它太多余了。其实我写的这一条也很多余，intern()方法还存在诸多的问题，如效率、实现上的不统一&#8230;&#8230;<br />
例子E：<br />
&nbsp;&nbsp; &nbsp;String str1 = "java";<br />
&nbsp;&nbsp; &nbsp;String str2 = new String("java");<br />
&nbsp;&nbsp; &nbsp;System.out.print(str1.equals(str2));<br />
无论在常量池还是堆中的对象，用equals()方法比较的就是内容，就这么简单！看完此条的人一定很后悔，但是在开始我劝你别看了&#8230;&#8230;<br />
<br />
后记：用彪哥的话说&#8220;有意思吗？&#8221;，确实没劲。在写这段的时候我也是思量再三，感觉自己像孔乙己炫耀&#8220;茴&#8221;字有几种写法。我查了一下茴 ，回，囘，囬，还有一种是&#8220;口&#8221;字里面有个&#8220;目&#8221;字，后面这四个都加上草字头&#8230;&#8230;<br />
<img src ="http://www.blogjava.net/EricGu/aggbug/284780.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2009-06-30 15:34 <a href="http://www.blogjava.net/EricGu/archive/2009/06/30/284780.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>FreeMarker设计指南(完整整理)</title><link>http://www.blogjava.net/EricGu/archive/2009/06/18/282974.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Thu, 18 Jun 2009 01:19:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2009/06/18/282974.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/282974.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2009/06/18/282974.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/282974.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/282974.html</trackback:ping><description><![CDATA[<h2>快速入门 </h2>
<h3>（1）模板 + 数据模型 = 输出 </h3>
<p>FreeMarker基于设计者和程序员是具有不同专业技能的不同个体的观念他们是分工劳动的：<br />
设计者专注于表示——创建HTML文件、图片、Web页面的其它可视化方面；<br />
程序员创建系统，生成设计页面要显示的数据。<br />
经常会遇到的问题是：在Web页面（或其它类型的文档）中显示的信息在设计页面时是无效的，是基于动态数据的。在这里，你可以在HTML（或其它要输出的文本）中加入一些特定指令，FreeMarker会在输出页面给最终用户时，用适当的数据替代这些代码。</p>
<br />
<p>先来解释一下freemaker的基本语法了，<br />
<font face="Courier New"><font color="#0000ff">&lt;# ... &gt;</font> 中存放所有freemaker的内容，之外的内容全部原样输出。<br />
<font color="#0000ff">&lt;@ ... /&gt;</font> 是函数调用<br />
两个定界符内的内容中，第一个符号表示指令或者函数名，其后的跟随参数。freemaker提供的控制包括如下：<br />
<font color="#0000ff">&lt;#if condition&gt;&lt;#elseif condition&gt;&lt;#else&gt;</font> 条件判断<br />
<font color="#0000ff">&lt;#list hash_or_seq as var&gt;</font> 遍历hash表或者collection（freemaker称作sequence）的成员<br />
<font color="#0000ff">&lt;#macro name param1 param2 ... &gt;&lt;#nested param&gt;</font> 宏，无返回参数<br />
<font color="#0000ff">&lt;#function name param1 param2&gt;&lt;#return val&gt;</font>函数，有返回参数<br />
<font color="#0000ff">var?member_function(...)</font> 用函数对var进行转换，freemaker称为build-ins。实际内部实现类似member_function(var, ...)<br />
<font color="#0000ff">stringA[M .. N]</font> 取子字符串，类似substring(stringA, M, N)<br />
<font color="#0000ff">{key:value, key2:value2 ...}</font> 直接定义一个hash表<br />
<font color="#0000ff">[item0, item1, item2 ...]</font> 直接定义一个序列<br />
<font color="#0000ff">hash0[key0]</font> 存取hash表中key对应的元素<br />
<font color="#0000ff">seq0[5]</font> 存取序列指定下标的元素<br />
<font color="#0000ff">&lt;@function1 param0 param1 ... /&gt;</font> 调用函数function1<br />
<font color="#0000ff">&lt;@macro0 param0 param1 ; nest_param0 nest_param1 ...&gt; nest_body &lt;</font></font><a><font face="Courier New" color="#0000ff">/@macro</font></a><font face="Courier New"><font color="#0000ff">&gt;</font> 调用宏，并处理宏的嵌套<br />
<font color="#0000ff">&lt;#assign var = value &gt;</font> 定义变量并初始化<br />
<font color="#0000ff">&lt;#local var = value&gt;</font> 在 macro 或者 function 中定义局部变量并初始化<br />
<font color="#0000ff">&lt;#global var = value &gt;</font> 定义全局变量并初始化<br />
<font color="#0000ff">${var}</font> 输出并替换为表达式的值<br />
<font color="#0000ff">&lt;#visit xmlnode&gt;</font> 调用macro匹配xmlnode本身及其子节点<br />
<font color="#0000ff">&lt;#recurse xmlnode&gt;</font> 调用macro匹配xmlnode的子节点</font></p>
<p><br />
</p>
<p>下面是一个例子： </p>
<pre>&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;title&gt;Welcome!&lt;/title&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;h1&gt;Welcome ${user}!&lt;/h1&gt;<br />
&lt;p&gt;Our latest product:<br />
&lt;a href="${latestProduct.url}"&gt;${latestProduct.name}&lt;/a&gt;!<br />
&lt;/body&gt;<br />
&lt;/html&gt;  <br />
</pre>
这个例子是在简单的HTML中加入了一些由${&#8230;}包围的特定代码，这些特定代码是FreeMarker的指令，而包含FreeMarker的指令的文件就称为模板（Template）。<br />
至于user、latestProduct.url和latestProduct.name来自于数据模型（data model）。<br />
数据模型由程序员编程来创建，向模板提供变化的信息，这些信息来自于数据库、文件，甚至于在程序中直接生成。<br />
模板设计者不关心数据从那儿来，只知道使用已经建立的数据模型。<br />
<p>下面是一个可能的数据模型： </p>
<pre>(root)<br />
|<br />
+- user = "Big Joe"<br />
|<br />
+- latestProduct<br />
|<br />
+- url = "products/greenmouse.html"<br />
|<br />
+- name = "green mouse"<br />
</pre>
数据模型类似于计算机的文件系统，latestProduct可以看作是目录。
<h3>2、数据模型 </h3>
<h4>（1）基础 </h4>
<p>在快速入门中介绍了在模板中使用的三种基本对象类型：scalars、hashes 和sequences，其实还可以有其它更多的能力： </p>
<ul>
    <li>scalars：存储单值 </li>
</ul>
<ul>
    <li>hashes：充当其它对象的容器，每个都关联一个唯一的查询名字 </li>
</ul>
<ul>
    <li>sequences：充当其它对象的容器，按次序访问 </li>
</ul>
<ul>
    <li>方法：通过传递的参数进行计算，以新对象返回结果 </li>
</ul>
<ul>
    <li>用户自定义FTL标记：宏和变换器 </li>
</ul>
<p>通常每个变量只具有上述的一种能力，但一个变量可以具有多个上述能力，如下面的例子： </p>
<pre>(root)<br />
|<br />
+- mouse = "Yerri"<br />
|<br />
+- age = 12<br />
|<br />
+- color = "brown"&gt;  <br />
</pre>
mouse既是scalars又是hashes，将上面的数据模型合并到下面的模板：
<pre>${mouse}       &lt;#-- use mouse as scalar --&gt;<br />
${mouse.age}   &lt;#-- use mouse as hash --&gt;<br />
${mouse.color} &lt;#-- use mouse as hash --&gt;  <br />
</pre>
输出结果是：
<pre>Yerri<br />
12<br />
brown  <br />
</pre>
<h4>（2）Scalar变量 </h4>
<p>Scalar变量存储单值，可以是： </p>
<ul>
    <li>字符串：简单文本，在模板中使用引号（单引号或双引号）括起 </li>
</ul>
<ul>
    <li>数字：在模板中直接使用数字值 </li>
</ul>
<ul>
    <li>日期：存储日期/时间相关的数据，可以是日期、时间或日期-时间（Timestamp）；通常情况，日期值由程序员加到数据模型中，设计者只需要显示它们 </li>
</ul>
<ul>
    <li>布尔值：true或false，通常在&lt;#if &#8230;&gt;标记中使用 </li>
</ul>
<h4>（3）hashes 、sequences和集合 </h4>
<p>有些变量不包含任何可显示的内容，而是作为容器包含其它变量，者有两种类型： </p>
<ul>
    <li>hashes：具有一个唯一的查询名字和它包含的每个变量相关联 </li>
</ul>
<ul>
    <li>sequences：使用数字和它包含的每个变量相关联，索引值从0开始 </li>
</ul>
<p>集合变量通常类似sequences，除非无法访问它的大小和不能使用索引来获得它的子变量；集合可以看作只能由&lt;#list &#8230;&gt;指令使用的受限sequences </p>
<h4>（4）方法 </h4>
<p>方法变量通常是基于给出的参数计算值。 </p>
<p>下面的例子假设程序员已经将方法变量avg放到数据模型中，用来计算数字平均值： </p>
<pre>The average of 3 and 5 is: ${avg(3, 5)}<br />
The average of 6 and 10 and 20 is: ${avg(6, 10, 20)}<br />
The average of the price of python and elephant is: <br />
${avg(animals.python.price, animals.elephant.price)}<br />
</pre>
<h4>（5）宏和变换器 </h4>
<p>宏和变换器变量是用户自定义指令（自定义FTL标记），会在后面讲述这些高级特性 </p>
<h4>（6）节点 </h4>
<p>节点变量表示为树型结构中的一个节点，通常在XML处理中使用，会在后面的专门章节中讲 </p>
<h3>3、模板 </h3>
<h4>（1）整体结构 </h4>
<p>模板使用FTL（FreeMarker模板语言）编写，是下面各部分的一个组合： </p>
<ul>
    <li>文本：直接输出
    <li>Interpolation：由${和}，或#{和}来限定，计算值替代输出
    <li>FTL标记：FreeMarker指令，和HTML标记类似，名字前加#予以区分，不会输出
    <li>注释：由&lt;#--和--&gt;限定，不会输出 </li>
</ul>
<p>下面是以一个具体模板例子： </p>
<pre>&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;title&gt;Welcome!&lt;/title&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;#-- Greet the user with his/her name --&gt;<br />
&lt;h1&gt;Welcome ${user}!&lt;/h1&gt;<br />
&lt;p&gt;We have these animals:<br />
&lt;ul&gt;<br />
&lt;#list animals as being&gt;<br />
&lt;li&gt;${being.name} for ${being.price} Euros<br />
&lt;/#list&gt;<br />
&lt;/ul&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;  <br />
</pre>
<p>注意事项： </p>
<ul>
    <li>FTL区分大小写，所以list是正确的FTL指令，而List不是；${name}和${NAME}是不同的 </li>
</ul>
<ul>
    <li>Interpolation只能在文本中使用 </li>
</ul>
<ul>
    <li>FTL标记不能位于另一个FTL标记内部，例如： </li>
</ul>
<pre>&lt;#if &lt;#include 'foo'&gt;='bar'&gt;...&lt;/if&gt;<br />
</pre>
<ul>
    <li>注释可以位于FTL标记和Interpolation内部，如下面的例子： </li>
</ul>
<pre>&lt;h1&gt;Welcome ${user &lt;#-- The name of user --&gt;}!&lt;/h1&gt;<br />
&lt;p&gt;We have these animals:<br />
&lt;ul&gt;<br />
&lt;#list &lt;#-- some comment... --&gt; animals as &lt;#-- again... --&gt; being&gt;<br />
...  <br />
</pre>
<ul>
    <li>余的空白字符会在模板输出时移除 </li>
</ul>
<h4>（2）指令 </h4>
<p>在FreeMarker中，使用FTL标记引用指令。有三种FTL标记，这和HTML标记是类似的： </p>
<ul>
    <li>开始标记：&lt;#directivename parameters&gt; </li>
</ul>
<ul>
    <li>结束标记：&lt;/#directivename&gt; </li>
</ul>
<ul>
    <li>空内容指令标记：&lt;#directivename parameters/&gt; </li>
</ul>
<p>有两种类型的指令：预定义指令和用户定义指令。 </p>
<p>用户定义指令要使用@替换#，如&lt;@mydirective&gt;...&lt;/@mydirective&gt;（会在后面讲述）。 </p>
<p>FTL标记不能够交叉，而应该正确的嵌套，如下面的代码是错误的： </p>
<pre>&lt;ul&gt;<br />
&lt;#list animals as being&gt;<br />
&lt;li&gt;${being.name} for ${being.price} Euros<br />
&lt;#if use = "Big Joe"&gt;<br />
(except for you)<br />
&lt;/#list&gt;<br />
&lt;/#if&gt; &lt;#-- WRONG! --&gt;<br />
&lt;/ul&gt;  <br />
</pre>
如果使用不存在的指令，FreeMarker不会使用模板输出，而是产生一个错误消息。
<p>FreeMarker会忽略FTL标记中的空白字符，如下面的例子： </p>
<pre>&lt;#list<br />
animals       as<br />
being<br />
&gt;<br />
${being.name} for ${being.price} Euros<br />
&lt;/#list    &gt;  <br />
</pre>
但是，&lt;、&lt;/和指令之间不允许有空白字符。
<h4>（3）表达式 </h4>
<p><strong>直接指定值</strong> </p>
<ul>
    <li>字符串 </li>
</ul>
使用单引号或双引号限定
<p>如果包含特殊字符需要转义，如下面的例子： </p>
<pre>${"It's \"quoted\" and<br />
this is a backslash: \\"}<br />
<br />
${'It\'s "quoted" and<br />
this is a backslash: \\'} <br />
</pre>
输出结果是：
<pre>It's "quoted" and<br />
this is a backslash: \<br />
<br />
It's "quoted" and<br />
this is a backslash: \ <br />
</pre>
下面是支持的转义序列：
<table class="wikitable" border="1">
    <tbody>
        <tr>
            <th>转义序列 </th>
            <th>含义 </th>
        </tr>
        <tr>
            <td>\" </td>
            <td>双引号(u0022) </td>
        </tr>
        <tr>
            <td>\' </td>
            <td>单引号(u0027) </td>
        </tr>
        <tr>
            <td><br />
            </td>
            <td>反斜杠(u005C) </td>
        </tr>
        <tr>
            <td>\n </td>
            <td>换行(u000A) </td>
        </tr>
        <tr>
            <td>\r </td>
            <td>Return (u000D) </td>
        </tr>
        <tr>
            <td>\t </td>
            <td>Tab (u0009) </td>
        </tr>
        <tr>
            <td>\b </td>
            <td>Backspace (u0008) </td>
        </tr>
        <tr>
            <td>\f </td>
            <td>Form feed (u000C) </td>
        </tr>
        <tr>
            <td>\l </td>
            <td>&lt; </td>
        </tr>
        <tr>
            <td>\g </td>
            <td>&gt; </td>
        </tr>
        <tr>
            <td>\a </td>
            <td>&amp; </td>
        </tr>
        <tr>
            <td>\{ </td>
            <td>{ </td>
        </tr>
        <tr>
            <td>\xCode </td>
            <td>4位16进制Unicode代码 </td>
        </tr>
    </tbody>
</table>
<p>有一类特殊的字符串称为raw字符串，被认为是纯文本，其中的\和{等不具有特殊含义，该类字符串在引号前面加r，下面是一个例子： </p>
<pre>${r"${foo}"}<br />
<br />
${r"C:\foo\bar"}  <br />
</pre>
输出的结果是：
<pre>${foo}<br />
<br />
C:\foo\bar  <br />
</pre>
<ul>
    <li>数字 </li>
</ul>
<p>直接输入，不需要引号 </p>
<p>精度数字使用&#8220;.&#8221;分隔，不能使用分组符号 </p>
<p>目前版本不支持科学计数法，所以&#8220;1E3&#8221;是错误的 </p>
<p>不能省略小数点前面的0，所以&#8220;.5&#8221;是错误的 </p>
<p>数字8、+8、08和8.00都是相同的 </p>
<ul>
    <li>布尔值 </li>
</ul>
<p>true和false，不使用引号 </p>
<ul>
    <li>序列 </li>
</ul>
<p>由逗号分隔的子变量列表，由方括号限定，下面是一个例子： </p>
<pre>&lt;#list ["winter", "spring", "summer", "autumn"] as x&gt;<br />
${x}<br />
&lt;/#list&gt; <br />
</pre>
输出的结果是：
<pre>winter<br />
spring<br />
summer<br />
autumn<br />
</pre>
列表的项目是表达式，所以可以有下面的例子：
<pre>[2 + 2, [1, 2, 3, 4], "whatnot"]<br />
</pre>
可以使用数字范围定义数字序列，例如2..5等同于[2, 3, 4, 5]，但是更有效率，注意数字范围没有方括号
<p>可以定义反递增的数字范围，如5..2 </p>
<ul>
    <li>散列（hash） </li>
</ul>
由逗号分隔的键/值列表，由大括号限定，键和值之间用冒号分隔，下面是一个例子：
<pre>{"name":"green mouse", "price":150}<br />
</pre>
键和值都是表达式，但是键必须是字符串
<p><strong>获取变量</strong> </p>
<ul>
    <li>顶层变量： ${variable}，变量名只能是字母、数字、下划线、$、@和#的组合，且不能以数字开头 </li>
</ul>
<ul>
    <li>从散列中获取数据 </li>
</ul>
<p>可以使用点语法或方括号语法，假设有下面的数据模型： </p>
<pre>(root)<br />
|<br />
+- book<br />
|   |<br />
|   +- title = "Breeding green mouses"<br />
|   |<br />
|   +- author<br />
|       |<br />
|       +- name = "Julia Smith"<br />
|       |<br />
|       +- info = "Biologist, 1923-1985, Canada"<br />
|<br />
+- test = "title" <br />
</pre>
下面都是等价的：
<pre>book.author.name<br />
book["author"].name<br />
book.author.["name"]<br />
book["author"]["name"]<br />
</pre>
使用点语法，变量名字有顶层变量一样的限制，但方括号语法没有该限制，因为名字是任意表达式的结果
<ul>
    <li>从序列获得数据：和散列的方括号语法语法一样，只是方括号中的表达式值必须是数字；注意：第一个项目的索引是0 </li>
</ul>
<p>序列片断：使用[startIndex..endIndex]语法，从序列中获得序列片断（也是序列）；startIndex和endIndex是结果为数字的表达式 </p>
<ul>
    <li>特殊变量：FreeMarker内定义变量，使用.variablename语法访问 </li>
</ul>
<p><strong>字符串操作 </strong></p>
<ul>
    <li>Interpolation（或连接操作） </li>
</ul>
<p>可以使用${..}（或#{..}）在文本部分插入表达式的值，例如： </p>
<pre>${"Hello ${user}!"}<br />
<br />
${"${user}${user}${user}${user}"}  <br />
</pre>
可以使用+操作符获得同样的结果
<pre>${"Hello " + user + "!"}<br />
<br />
${user + user + user + user}<br />
</pre>
${..}只能用于文本部分，下面的代码是错误的：
<pre>&lt;#if ${isBig}&gt;Wow!&lt;/#if&gt;<br />
<br />
&lt;#if "${isBig}"&gt;Wow!&lt;/#if&gt;<br />
</pre>
应该写成：
<pre>&lt;#if isBig&gt;Wow!&lt;/#if&gt;<br />
</pre>
<ul>
    <li>子串 </li>
</ul>
<p>例子（假设user的值为&#8220;Big Joe&#8221;）： </p>
<pre>${user[0]}${user[4]}<br />
<br />
${user[1..4]}<br />
</pre>
结果是（注意第一个字符的索引是0）：
<pre>BJ<br />
<br />
ig J <br />
</pre>
<strong>序列操作 </strong>
<ul>
    <li>连接操作：和字符串一样，使用+，下面是一个例子： </li>
</ul>
<pre>&lt;#list ["Joe", "Fred"] + ["Julia", "Kate"] as user&gt;<br />
- ${user}<br />
&lt;/#list&gt;<br />
</pre>
输出结果是：
<pre>- Joe<br />
- Fred<br />
- Julia<br />
- Kate<br />
</pre>
<strong>散列操作 </strong>
<ul>
    <li>连接操作：和字符串一样，使用+，如果具有相同的key，右边的值替代左边的值，例如： </li>
</ul>
<pre>&lt;#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}&gt;<br />
- Joe is ${ages.Joe}<br />
- Fred is ${ages.Fred}<br />
- Julia is ${ages.Julia}  <br />
</pre>
输出结果是：
<pre>- Joe is 30<br />
- Fred is 25<br />
- Julia is 18  <br />
</pre>
<strong>算术运算 </strong>
<ul>
    <li>＋、－、&#215;、／、％，下面是一个例子： </li>
</ul>
<pre>${x * x - 100}<br />
${x / 2}<br />
${12 % 10}<br />
</pre>
输出结果是（假设x为5）：
<pre>-75<br />
2.5<br />
2  <br />
</pre>
操作符两边必须是数字，因此下面的代码是错误的：
<pre>${3 * "5"} &lt;#-- WRONG! --&gt;  <br />
</pre>
使用+操作符时，如果一边是数字，一边是字符串，就会自动将数字转换为字符串，例如：
<pre>${3 + "5"}  <br />
</pre>
输出结果是：
<pre>35<br />
</pre>
使用内建的int（后面讲述）获得整数部分，例如：
<pre>${(x/2)?int}<br />
${1.1?int}<br />
${1.999?int}<br />
${-1.1?int}<br />
${-1.999?int}<br />
</pre>
输出结果是（假设x为5）：
<pre>2<br />
1<br />
1<br />
-1<br />
-1<br />
</pre>
<ul>
    <li>比较操作符 </li>
</ul>
<p>使用=（或==，完全相等）测试两个值是否相等，使用!= 测试两个值是否不相等 </p>
<p>=和!=两边必须是相同类型的值，否则会产生错误，例如&lt;#if 1 = "1"&gt;会引起错误 </p>
<p>Freemarker是精确比较，所以对"x"、"x "和"X"是不相等的 </p>
<p>对数字和日期可以使用&lt;、&lt;=、&gt;和&gt;=，但不能用于字符串 </p>
<p>由于Freemarker会将&gt;解释成FTL标记的结束字符，所以对于&gt;和&gt;=可以使用括号来避免这种情况，例如&lt;#if (x &gt; y)&gt; </p>
<p>另一种替代的方法是，使用lt、lte、gt和gte来替代&lt;、&lt;=、&gt;和&gt;= </p>
<ul>
    <li>逻辑操作符 </li>
</ul>
<p>&amp;&amp;（and）、||（or）、!（not），只能用于布尔值，否则会产生错误 </p>
<p>例子： </p>
<pre>&lt;#if x &lt; 12 &amp;&amp; color = "green"&gt;<br />
We have less than 12 things, and they are green.<br />
&lt;/#if&gt;<br />
&lt;#if !hot&gt; &lt;#-- here hot must be a boolean --&gt;<br />
It's not hot.<br />
&lt;/#if&gt;  <br />
</pre>
<ul>
    <li>内建函数 </li>
</ul>
<p>内建函数的用法类似访问散列的子变量，只是使用&#8220;?&#8221;替代&#8220;.&#8221;，下面列出常用的一些函数 </p>
<ul>
    <li>
    <ul>
        <li>字符串使用的： </li>
    </ul>
    </li>
</ul>
<p>html：对字符串进行HTML编码 </p>
<p>cap_first：使字符串第一个字母大写 </p>
<p>lower_case：将字符串转换成小写 </p>
<p>upper_case：将字符串转换成大写 </p>
<p>trim：去掉字符串前后的空白字符 </p>
<ul>
    <li>
    <ul>
        <li>序列使用的： </li>
    </ul>
    </li>
</ul>
<p>size：获得序列中元素的数目 </p>
<ul>
    <li>
    <ul>
        <li>数字使用的： </li>
    </ul>
    </li>
</ul>
<p>int：取得数字的整数部分（如-1.9?int的结果是-1） </p>
<p>例子（假设test保存字符串"Tom &amp; Jerry"）： </p>
<pre>${test?html}<br />
${test?upper_case?html}<br />
</pre>
输出结果是：
<pre>Tom &amp;amp; Jerry<br />
TOM &amp;amp; JERRY  <br />
</pre>
<ul>
    <li>操作符优先顺序 </li>
</ul>
<table class="wikitable" border="1">
    <tbody>
        <tr>
            <th>操作符组 </th>
            <th>操作符 </th>
        </tr>
        <tr>
            <td>后缀 </td>
            <td>[subvarName] [subStringRange] . (methodParams) </td>
        </tr>
        <tr>
            <td>一元 </td>
            <td>+expr、-expr、! </td>
        </tr>
        <tr>
            <td>内建 </td>
            <td>? </td>
        </tr>
        <tr>
            <td>乘法 </td>
            <td>*、 / 、% </td>
        </tr>
        <tr>
            <td>加法 </td>
            <td>+、- </td>
        </tr>
        <tr>
            <td>关系 </td>
            <td>&lt;、&gt;、&lt;=、&gt;=（lt、lte、gt、gte） </td>
        </tr>
        <tr>
            <td>相等 </td>
            <td>==（=）、!= </td>
        </tr>
        <tr>
            <td>逻辑and </td>
            <td>&amp;&amp; </td>
        </tr>
        <tr>
            <td>逻辑or </td>
            <td>双竖线</td>
        </tr>
        <tr>
            <td>数字范围 </td>
            <td>.. </td>
        </tr>
    </tbody>
</table>
<h4>（4）Interpolation </h4>
<p>Interpolation有两种类型： </p>
<ol>
    <li>通用Interpolation：${expr} </li>
</ol>
<ol>
    <li>数字Interpolation：#{expr}或#{expr; format} </li>
</ol>
<p>注意：Interpolation只能用于文本部分 </p>
<ul>
    <li>通用Interpolation </li>
</ul>
<p>插入字符串值：直接输出表达式结果 </p>
<p>插入数字值：根据缺省格式（由#setting指令设置）将表达式结果转换成文本输出；可以使用内建函数string格式化单个Interpolation，下面是一个例子： </p>
<pre>&lt;#setting number_format="currency"/&gt;<br />
&lt;#assign answer=42/&gt;<br />
${answer}<br />
${answer?string}  &lt;#-- the same as ${answer} --&gt;<br />
${answer?string.number}<br />
${answer?string.currency}<br />
${answer?string.percent} <br />
</pre>
输出结果是：
<pre>$42.00<br />
$42.00<br />
42<br />
$42.00<br />
4,200%<br />
</pre>
插入日期值：根据缺省格式（由#setting指令设置）将表达式结果转换成文本输出；可以使用内建函数string格式化单个Interpolation，下面是一个使用格式模式的例子：
<pre>${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")}<br />
${lastUpdated?string("EEE, MMM d, ''yy")}<br />
${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")}  <br />
</pre>
输出的结果类似下面的格式：
<pre>2003-04-08 21:24:44 Pacific Daylight Time<br />
Tue, Apr 8, '03<br />
Tuesday, April 08, 2003, 09:24:44 PM (PDT)<br />
</pre>
插入布尔值：根据缺省格式（由#setting指令设置）将表达式结果转换成文本输出；可以使用内建函数string格式化单个Interpolation，下面是一个例子：
<pre>&lt;#assign foo=true/&gt;<br />
${foo?string("yes", "no")}<br />
</pre>
输出结果是：
<pre>yes<br />
</pre>
<ul>
    <li>数字Interpolation的#{expr; format}形式可以用来格式化数字，format可以是： </li>
</ul>
<p>mX：小数部分最小X位 </p>
<p>MX：小数部分最大X位 </p>
<p>例子： </p>
<pre>&lt;#-- If the language is US English the output is: --&gt;<br />
&lt;#assign x=2.582/&gt;<br />
&lt;#assign y=4/&gt;<br />
#{x; M2}   &lt;#-- 2.58 --&gt;<br />
#{y; M2}   &lt;#-- 4    --&gt;<br />
#{x; m1}   &lt;#-- 2.6 --&gt;<br />
#{y; m1}   &lt;#-- 4.0 --&gt;<br />
#{x; m1M2} &lt;#-- 2.58 --&gt;<br />
#{y; m1M2} &lt;#-- 4.0  --&gt;  <br />
</pre>
<h3>4、杂项 </h3>
<h4>（1）用户定义指令 </h4>
<p>宏和变换器变量是两种不同类型的用户定义指令，它们之间的区别是宏是在模板中使用macro指令定义，而变换器是在模板外由程序定义，这里只介绍宏 </p>
<ul>
    <li>基本用法 </li>
</ul>
<p>宏是和某个变量关联的模板片断，以便在模板中通过用户定义指令使用该变量，下面是一个例子： </p>
<pre>&lt;#macro greet&gt;<br />
&lt;font size="+2"&gt;Hello Joe!&lt;/font&gt;<br />
&lt;/#macro&gt;  <br />
</pre>
作为用户定义指令使用宏变量时，使用@替代FTL标记中的#
<pre>&lt;@greet&gt;&lt;/@greet&gt;<br />
</pre>
如果没有体内容，也可以使用：
<pre>&lt;@greet/&gt;<br />
</pre>
<ul>
    <li>参数 </li>
</ul>
<p>在macro指令中可以在宏变量之后定义参数，如： </p>
<pre>&lt;#macro greet person&gt;<br />
&lt;font size="+2"&gt;Hello ${person}!&lt;/font&gt;<br />
&lt;/#macro&gt; <br />
</pre>
可以这样使用这个宏变量：
<pre>&lt;@greet person="Fred"/&gt; and &lt;@greet person="Batman"/&gt; <br />
</pre>
输出结果是：
<pre>  &lt;font size="+2"&gt;Hello Fred!&lt;/font&gt;<br />
<br />
and   &lt;font size="+2"&gt;Hello Batman!&lt;/font&gt;<br />
</pre>
<p>宏的参数是FTL表达式，所以下面的代码具有不同的意思： </p>
<pre>&lt;@greet person=Fred/&gt;<br />
</pre>
这意味着将Fred变量的值传给person参数，该值不仅是字符串，还可以是其它类型，甚至是复杂的表达式
<p>可以有多参数，下面是一个例子： </p>
<pre>&lt;#macro greet person color&gt;<br />
&lt;font size="+2" color="${color}"&gt;Hello ${person}!&lt;/font&gt;<br />
&lt;/#macro&gt; <br />
</pre>
可以这样使用该宏变量：
<pre>&lt;@greet person="Fred" color="black"/&gt; <br />
</pre>
其中参数的次序是无关的，因此下面是等价的：
<pre>&lt;@greet color="black" person="Fred"/&gt;<br />
</pre>
只能使用在macro指令中定义的参数，并且对所有参数赋值，所以下面的代码是错误的：
<pre>&lt;@greet person="Fred" color="black" background="green"/&gt;<br />
&lt;@greet person="Fred"/&gt;<br />
</pre>
可以在定义参数时指定缺省值，如：
<pre>&lt;#macro greet person color="black"&gt;<br />
&lt;font size="+2" color="${color}"&gt;Hello ${person}!&lt;/font&gt;<br />
&lt;/#macro&gt;  <br />
</pre>
这样&lt;@greet person="Fred"/&gt;就正确了
<p>宏的参数是局部变量，只能在宏定义中有效 </p>
<ul>
    <li>嵌套内容 </li>
</ul>
<p>用户定义指令可以有嵌套内容，使用&lt;#nested&gt;指令执行指令开始和结束标记之间的模板片断 </p>
<p>例子： </p>
<pre>&lt;#macro border&gt;<br />
&lt;table border=4 cellspacing=0 cellpadding=4&gt;&lt;tr&gt;&lt;td&gt;<br />
&lt;#nested&gt;<br />
&lt;/tr&gt;&lt;/td&gt;&lt;/table&gt;<br />
&lt;/#macro&gt;  <br />
</pre>
这样使用该宏变量：
<pre>&lt;@border&gt;The bordered text&lt;/@border&gt;<br />
</pre>
输出结果：
<pre>  &lt;table border=4 cellspacing=0 cellpadding=4&gt;&lt;tr&gt;&lt;td&gt;<br />
The bordered text<br />
&lt;/tr&gt;&lt;/td&gt;&lt;/table&gt;<br />
</pre>
<p>&lt;#nested&gt;指令可以被多次调用，例如： </p>
<pre>&lt;#macro do_thrice&gt;<br />
&lt;#nested&gt;<br />
&lt;#nested&gt;<br />
&lt;#nested&gt;<br />
&lt;/#macro&gt;<br />
&lt;@do_thrice&gt;<br />
Anything.<br />
&lt;/@do_thrice&gt;  <br />
</pre>
输出结果：
<pre>  Anything.<br />
Anything.<br />
Anything. <br />
</pre>
嵌套内容可以是有效的FTL，下面是一个有些复杂的例子： <tt>&lt;@border&gt; &lt;ul&gt; &lt;@do_thrice&gt; &lt;li&gt;&lt;@greet person="Joe"/&gt; &lt;/@do_thrice&gt; &lt;/ul&gt; &lt;/@border&gt; }}} 输出结果：
<pre>  &lt;table border=4 cellspacing=0 cellpadding=4&gt;&lt;tr&gt;&lt;td&gt;<br />
&lt;ul&gt;<br />
&lt;li&gt;&lt;font size="+2"&gt;Hello Joe!&lt;/font&gt;<br />
&lt;li&gt;&lt;font size="+2"&gt;Hello Joe!&lt;/font&gt;<br />
&lt;li&gt;&lt;font size="+2"&gt;Hello Joe!&lt;/font&gt;<br />
&lt;/ul&gt;<br />
&lt;/tr&gt;&lt;/td&gt;&lt;/table&gt;  <br />
</pre>
宏定义中的局部变量对嵌套内容是不可见的，例如：
<pre>&lt;#macro repeat count&gt;<br />
&lt;#local y = "test"&gt;<br />
&lt;#list 1..count as x&gt;<br />
${y} ${count}/${x}: &lt;#nested&gt;<br />
&lt;/#list&gt;<br />
&lt;/#macro&gt;<br />
&lt;@repeat count=3&gt;${y?default("?")} ${x?default("?")} ${count?default("?")}&lt;/@repeat&gt;<br />
</pre>
输出结果：
<pre>    test 3/1: ? ? ?<br />
test 3/2: ? ? ?<br />
test 3/3: ? ? ?<br />
</pre>
<ul>
    <li>在宏定义中使用循环变量 </li>
</ul>
<p>用户定义指令可以有循环变量，通常用于重复嵌套内容，基本用法是：作为nested指令的参数传递循环变量的实际值，而在调用用户定义指令时，在&lt;@&#8230;&gt;开始标记的参数后面指定循环变量的名字 </p>
<p>例子： </p>
<pre>&lt;#macro repeat count&gt;<br />
&lt;#list 1..count as x&gt;<br />
&lt;#nested x, x/2, x==count&gt;<br />
&lt;/#list&gt;<br />
&lt;/#macro&gt;<br />
&lt;@repeat count=4 ; c, halfc, last&gt;<br />
${c}. ${halfc}&lt;#if last&gt; Last!&lt;/#if&gt;<br />
&lt;/@repeat&gt;  <br />
</pre>
输出结果：
<pre>  1. 0.5<br />
2. 1<br />
3. 1.5<br />
4. 2 Last!<br />
</pre>
<p>指定的循环变量的数目和用户定义指令开始标记指定的不同不会有问题 </p>
<p>调用时少指定循环变量，则多指定的值不可见 </p>
<p>调用时多指定循环变量，多余的循环变量不会被创建 </p>
<h4>（2）在模板中定义变量 </h4>
<p>在模板中定义的变量有三种类型： </p>
<ul>
    <li>plain变量：可以在模板的任何地方访问，包括使用include指令插入的模板，使用assign指令创建和替换 </li>
</ul>
<ul>
    <li>局部变量：在宏定义体中有效，使用local指令创建和替换 </li>
</ul>
<ul>
    <li>循环变量：只能存在于指令的嵌套内容，由指令（如list）自动创建 </li>
</ul>
<p>宏的参数是局部变量，而不是循环变量；局部变量隐藏（而不是覆盖）同名的plain变量；循环变量隐藏同名的局部变量和plain变量，下面是一个例子： </p>
<pre>&lt;#assign x = "plain"&gt;<br />
1. ${x}  &lt;#-- we see the plain var. here --&gt;<br />
&lt;@test/&gt;<br />
6. ${x}  &lt;#-- the value of plain var. was not changed --&gt;<br />
&lt;#list ["loop"] as x&gt;<br />
7. ${x}  &lt;#-- now the loop var. hides the plain var. --&gt;<br />
&lt;#assign x = "plain2"&gt; &lt;#-- replace the plain var, hiding does not mater here --&gt;<br />
8. ${x}  &lt;#-- it still hides the plain var. --&gt;<br />
&lt;/#list&gt;<br />
9. ${x}  &lt;#-- the new value of plain var. --&gt;<br />
&lt;#macro test&gt;<br />
2. ${x}  &lt;#-- we still see the plain var. here --&gt;<br />
&lt;#local x = "local"&gt;<br />
3. ${x}  &lt;#-- now the local var. hides it --&gt;<br />
&lt;#list ["loop"] as x&gt;<br />
4. ${x}  &lt;#-- now the loop var. hides the local var. --&gt;<br />
&lt;/#list&gt;<br />
5. ${x}  &lt;#-- now we see the local var. again --&gt;<br />
&lt;/#macro&gt;  <br />
</pre>
输出结果：
<pre>1. plain<br />
2. plain<br />
3. local<br />
4. loop<br />
5. local<br />
6. plain<br />
7. loop<br />
8. loop<br />
9. plain2<br />
</pre>
<p>内部循环变量隐藏同名的外部循环变量，如： </p>
<pre>&lt;#list ["loop 1"] as x&gt;<br />
${x}<br />
&lt;#list ["loop 2"] as x&gt;<br />
${x}<br />
&lt;#list ["loop 3"] as x&gt;<br />
${x}<br />
&lt;/#list&gt;<br />
${x}<br />
&lt;/#list&gt;<br />
${x}<br />
&lt;/#list&gt;<br />
</pre>
输出结果：
<pre>  loop 1<br />
loop 2<br />
loop 3<br />
loop 2<br />
loop 1 <br />
</pre>
模板中的变量会隐藏（而不是覆盖）数据模型中同名变量，如果需要访问数据模型中的同名变量，使用特殊变量global，下面的例子假设数据模型中的user的值是Big Joe：
<pre>&lt;#assign user = "Joe Hider"&gt;<br />
${user}          &lt;#-- prints: Joe Hider --&gt;<br />
${.globals.user} &lt;#-- prints: Big Joe --&gt;  <br />
</pre>
<h4>（3）名字空间 </h4>
<p>通常情况，只使用一个名字空间，称为主名字空间 </p>
<p>为了创建可重用的宏、变换器或其它变量的集合（通常称库），必须使用多名字空间，其目的是防止同名冲突 </p>
<ul>
    <li>创建库 </li>
</ul>
<p>下面是一个创建库的例子（假设保存在lib/my_test.ftl中）： </p>
<pre>&lt;#macro copyright date&gt;<br />
&lt;p&gt;Copyright (C) ${date} Julia Smith. All rights reserved.<br />
&lt;br&gt;Email: ${mail}&lt;/p&gt;<br />
&lt;/#macro&gt;  <br />
&lt;#assign mail = "jsmith@acme.com"&gt; <br />
</pre>
使用import指令导入库到模板中，Freemarker会为导入的库创建新的名字空间，并可以通过import指令中指定的散列变量访问库中的变量：
<pre>&lt;#import "/lib/my_test.ftl" as my&gt;<br />
&lt;#assign mail="fred@acme.com"&gt;<br />
&lt;@my.copyright date="1999-2002"/&gt;<br />
${my.mail}<br />
${mail}  <br />
</pre>
输出结果：
<pre>  &lt;p&gt;Copyright (C) 1999-2002 Julia Smith. All rights reserved.<br />
&lt;br&gt;Email: jsmith@acme.com&lt;/p&gt;<br />
jsmith@acme.com<br />
fred@acme.com  <br />
</pre>
可以看到例子中使用的两个同名变量并没有冲突，因为它们位于不同的名字空间
<p>可以使用assign指令在导入的名字空间中创建或替代变量，下面是一个例子： </p>
<pre>&lt;#import "/lib/my_test.ftl" as my&gt;<br />
${my.mail}<br />
&lt;#assign mail="jsmith@other.com" in my&gt;<br />
${my.mail}  <br />
</pre>
输出结果：
<pre>jsmith@acme.com<br />
jsmith@other.com  <br />
</pre>
数据模型中的变量任何地方都可见，也包括不同的名字空间，下面是修改的库：
<pre>&lt;#macro copyright date&gt;<br />
&lt;p&gt;Copyright (C) ${date} ${user}. All rights reserved.&lt;/p&gt;<br />
&lt;/#macro&gt;<br />
&lt;#assign mail = "${user}@acme.com"&gt;   <br />
</pre>
假设数据模型中的user变量的值是Fred，则下面的代码：
<pre>&lt;#import "/lib/my_test.ftl" as my&gt;<br />
&lt;@my.copyright date="1999-2002"/&gt;<br />
${my.mail}   <br />
</pre>
输出结果：
<pre>  &lt;p&gt;Copyright (C) 1999-2002 Fred. All rights reserved.&lt;/p&gt;<br />
Fred@acme.com   <br />
<br />
<strong><br />
补充（静态方法的调用）：</strong><br />
<br />
<strong>方法1：</strong><br />
<span class="comment">##定义配置文件 freemarkerstatic.properties</span> <br />
<span class="ident">_Validator</span><span class="punct">=</span><span class="ident">com</span><span class="punct">.</span><span class="ident">longyou</span><span class="punct">.</span><span class="ident">util</span><span class="punct">.</span><span class="ident">Validator</span> <br />
<span class="ident">_Functions</span><span class="punct">=</span><span class="ident">com</span><span class="punct">.</span><span class="ident">longyou</span><span class="punct">.</span><span class="ident">util</span><span class="punct">.</span><span class="ident">Functions</span> <br />
<span class="ident">_EscapeUtils</span><span class="punct">=</span><span class="ident">com</span><span class="punct">.</span><span class="ident">longyou</span><span class="punct">.</span><span class="ident">util</span><span class="punct">.</span><span class="ident">EscapeUtils</span> <br />
<span class="punct">/调用代码</span> <br />
<span class="global">${</span><span class="ident">_Functions</span><span class="punct">.</span><span class="ident">toUpperCase</span><span class="punct">("</span><span class="string">Hello</span><span class="punct">")}&lt;</span><span class="ident">br</span><span class="punct">&gt;</span> <br />
<span class="global">${</span><span class="ident">_EscapeUtils</span><span class="punct">.</span><span class="ident">escape</span><span class="punct">("</span><span class="string">狼的原野</span><span class="punct">")}<br />
<br />
<strong>方法2：</strong><br />
</span>${stack.findValue("@package.ClassName@method")}<br />
<br />
<br />
<font size="5"><strong>补充：常用语法</strong></font></pre>
</tt>
<p>EG.一个对象BOOK</p>
<p>1.输出 ${book.name}</p>
<p>空值判断：${book.name?if_exists },</p>
<p>${book.name?default(&#8216;xxx&#8217;)}//默认值xxx</p>
<p>${ book.name!"xxx"}//默认值xxx</p>
<p>日期格式：${book.date?string('yyyy-MM-dd')}</p>
<p>数字格式：${book?string.number}--20</p>
<p>${book?string.currency}--&lt;#-- $20.00 --&gt;</p>
<p>${book?string.percent}—&lt;#-- 20% --&gt;</p>
<p>插入布尔值：</p>
<p>&lt;#assign foo=ture /&gt;</p>
<p>${foo?string("yes","no")} &lt;#-- yes --&gt;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>2．逻辑判断</p>
<p>a:</p>
<p>&lt;#if condition&gt;...</p>
<p>&lt;#elseif condition2&gt;...</p>
<p>&lt;#elseif condition3&gt;......</p>
<p>&lt;#else&gt;...</p>
<p>其中空值判断可以写成&lt;#if book.name?? &gt;</p>
<p>&nbsp;</p>
<p>b:</p>
<p>&lt;#switch value&gt;</p>
<p>&lt;#case refValue1&gt;</p>
<p>...</p>
<p>&lt;#break&gt;</p>
<p>&lt;#case refValue2&gt;</p>
<p>...</p>
<p>&lt;#break&gt;</p>
<p>...</p>
<p>&lt;#case refValueN&gt;</p>
<p>...</p>
<p>&lt;#break&gt;</p>
<p>&lt;#default&gt;</p>
<p>...</p>
<p>&nbsp;</p>
<p>3．循环读取</p>
<p>&lt;#list sequence as item&gt;</p>
<p>...</p>
<p>空值判断&lt;#if bookList?size = 0&gt;</p>
<p>e.g.</p>
<p>&lt;#list employees as e&gt;</p>
<p>${e_index}. ${e.name}</p>
<p>输出:</p>
<p>1. Readonly</p>
<p>2. Robbin</p>
<strong><br />
freemarker中Map的使用</strong><br />
<font color="#999900" size="2"><span>&lt;</span><span>#list testMap?keys as testKey&gt; </span><br />
<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;</span> <span>option</span> <span>value</span><span>="</span><span>${testKey}</span><span>"</span> <span>&gt;</span></font>
<div><font color="#999900" size="2"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span>${</span><span>testMap</span><span>[</span><span>testKey</span><span>]}</span> </font></div>
<div><font size="2"><span><font color="#999900">&nbsp;&nbsp;&nbsp;&nbsp; &lt;/</font></span></font><font color="#999900" size="2"><span>option&gt; <br />
&lt;</span><span>/</span><span>#list&gt;</span></font></div>
<tt>
<pre><br />
freemarker的Eclipse插件<br />
</pre>
</tt>
<ul>
    <li>If you use Eclipse 2.x:
    <ol>
        <li>Open the <strong>Window</strong> menu, then <strong>Open Perspective</strong> -&gt; <strong>Install/Update</strong>
        <li>Click with the right mouse button on the <strong>Feature Updates</strong> view, then select <strong>New</strong> -&gt; <strong>Site Bookmark</strong>
        <li>In the displayed dialog box, type <strong>"FreeMarker"</strong> for Name and <strong>"http://www.freemarker.org/eclipse/update"</strong> for URL. Leave the "Bookmark type" radio buttons on "Eclipse update site".
        <li>Click <strong>Finish</strong>
        <li>Open the tree node under the newly created update site named "FreeMarker", select the <strong>"FreeMarker <em>X.Y.Z</em>"</strong> feature, and install it using the <strong>Install now</strong> button in the preview pane. </li>
    </ol>
    <li>If you use Eclipse 3.x:
    <ol>
        <li><strong>Help</strong> -&gt; <strong>Software updates</strong> -&gt; <strong>Find and install...</strong>.
        <li>Choose "Search for new features to install".
        <li>Click <strong>Add Update Site...</strong>, and type <strong>"FreeMarker"</strong> for Name and <strong>"http://www.freemarker.org/eclipse/update"</strong> for URL.
        <li>Check the box of the "FreeMarker" feature.
        <li>"Next"-s until it is installed... </li>
    </ol>
    </li>
</ul>
<img src ="http://www.blogjava.net/EricGu/aggbug/282974.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2009-06-18 09:19 <a href="http://www.blogjava.net/EricGu/archive/2009/06/18/282974.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>J2SE5中的最新注释功能SuppressWarnings </title><link>http://www.blogjava.net/EricGu/archive/2009/06/16/282626.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Tue, 16 Jun 2009 08:02:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2009/06/16/282626.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/282626.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2009/06/16/282626.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/282626.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/282626.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: 一、什么是注释                         &nbsp;&nbsp;&nbsp; 说起注释，得先提一提什么是元数据(metadata)。所谓元数据就是数据的数据。也就是说，元数据是描述数据的。就象数据表中的字段一样，每个字段描述了这个字段下的数据的含义。而J2SE5.0中提供的注释就是java源代码的元数据，也就是说注释是描述java源代码的。在J2SE5.0中可以自定...&nbsp;&nbsp;<a href='http://www.blogjava.net/EricGu/archive/2009/06/16/282626.html'>阅读全文</a><img src ="http://www.blogjava.net/EricGu/aggbug/282626.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2009-06-16 16:02 <a href="http://www.blogjava.net/EricGu/archive/2009/06/16/282626.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>IntelliJ Idea 常用快捷键列表</title><link>http://www.blogjava.net/EricGu/archive/2009/03/26/262020.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Thu, 26 Mar 2009 01:35:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2009/03/26/262020.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/262020.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2009/03/26/262020.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/262020.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/262020.html</trackback:ping><description><![CDATA[<p>Alt+回车 导入包,自动修正<span style="display: none"> Y#a 5Q;%C </span>&nbsp;<br />
Ctrl+N&nbsp; 查找类<span style="display: none"> }8dN-@% </span>&nbsp;<br />
Ctrl+Shift+N 查找文件<span style="display: none"> \$:/ad </span>&nbsp;<br />
Ctrl+Alt+L&nbsp; 格式化代码<span style="display: none"> ^vz&gt;q?)N </span>&nbsp;<br />
Ctrl+Alt+O 优化导入的类和包<span style="display: none"> d B)QPI$ </span>&nbsp;<br />
Alt+Insert 生成代码(如get,set方法,构造函数等)<span style="display: none"> 8 A,,7dI </span>&nbsp;<br />
Ctrl+E或者Alt+Shift+C&nbsp; 最近更改的代码<span style="display: none"> {dS(}X&amp;qw- </span>&nbsp;<br />
Ctrl+R 替换文本<span style="display: none"> m[NkF4K` </span>&nbsp;<br />
Ctrl+F 查找文本<span style="display: none"> nRgAKNV ) </span>&nbsp;<br />
Ctrl+Shift+Space 自动补全代码<span style="display: none"> ',+6'2ex </span>&nbsp;<br />
Ctrl+空格 代码提示<span style="display: none"> k-1Xx&gt;g </span>&nbsp;<br />
Ctrl+Alt+Space 类名或接口名提示<span style="display: none"> vgX;@  </span>&nbsp;<br />
Ctrl+P 方法参数提示<span style="display: none"> V#" )7P </span>&nbsp;<br />
Ctrl+Shift+Alt+N 查找类中的方法或变量<span style="display: none"> =1ov </span>&nbsp;<br />
Alt+Shift+C 对比最近修改的代码<span style="display: none"> r?PrlqOM </span>&nbsp;<br />
<span style="display: none"> B[+:q]7 </span>&nbsp;<br />
Shift+F6&nbsp; 重构-重命名<span style="display: none"> H["Jg)kJ </span>&nbsp;<br />
Ctrl+Shift+先上键<span style="display: none"> ==ko,FJSV </span>&nbsp;<br />
Ctrl+X 删除行<span style="display: none"> rL 2+5| </span>&nbsp;<br />
Ctrl+D 复制行<span style="display: none"> gJmr $ </span>&nbsp;<br />
Ctrl+/ 或 Ctrl+Shift+/&nbsp; 注释（// 或者/*...*/ ）<span style="display: none"> hrkkRl </span>&nbsp;<br />
Ctrl+J&nbsp; 自动代码<span style="display: none"> i*+'FH </span>&nbsp;<br />
Ctrl+E 最近打开的文件<span style="display: none"> TM~yQ6K </span>&nbsp;<br />
Ctrl+H 显示类结构图<span style="display: none"> 7OE|# </span>&nbsp;<br />
Ctrl+Q 显示注释文档<span style="display: none"> (LlsVoL2 </span>&nbsp;<br />
Alt+F1 查找代码所在位置<span style="display: none"> Fv}![ 7| </span>&nbsp;<br />
Alt+1 快速打开或隐藏工程面板<span style="display: none"> ]N='WJ(8/ </span>&nbsp;<br />
Ctrl+Alt+ left/right 返回至上次浏览的位置<span style="display: none"> A[b.}3%f </span>&nbsp;<br />
Alt+ left/right 切换代码视图<span style="display: none"> XnN*gM l! </span>&nbsp;<br />
Alt+ Up/Down 在方法间快速移动定位<span style="display: none"> ^N=&lt;b0rq </span>&nbsp;<br />
Ctrl+Shift+Up/Down 代码向上/下移动。<span style="display: none"> m4$mF/-Ny+ </span>&nbsp;<br />
F2 或Shift+F2 高亮错误或警告快速定位<span style="display: none"> %}V4b </span>&nbsp;<br />
<span style="display: none">wsPWQvT </span>&nbsp;<br />
代码标签输入完成后，按Tab，生成代码。<span style="display: none"> &amp;3"n7 fmT </span>&nbsp;<br />
选中文本，按Ctrl+Shift+F7 ，高亮显示所有该文本，按Esc高亮消失。<span style="display: none"> 5H`rQKU </span>&nbsp;<br />
Ctrl+W 选中代码，连续按会有其他效果<span style="display: none"> Ia87 </span>&nbsp;<br />
选中文本，按Alt+F3 ，逐个往下查找相同文本，并高亮显示。<span style="display: none"> ?Ge~7h- </span>&nbsp;<br />
Ctrl+Up/Down 光标跳转到第一行或最后一行下<span style="display: none"> m@eohmV&gt; </span>&nbsp;<br />
Ctrl+B 快速打开光标处的类或方法 </p>
<img src ="http://www.blogjava.net/EricGu/aggbug/262020.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2009-03-26 09:35 <a href="http://www.blogjava.net/EricGu/archive/2009/03/26/262020.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>IntelliJ IDEA使用技巧一览表</title><link>http://www.blogjava.net/EricGu/archive/2009/03/26/262019.html</link><dc:creator>Eric Gu</dc:creator><author>Eric Gu</author><pubDate>Thu, 26 Mar 2009 01:33:00 GMT</pubDate><guid>http://www.blogjava.net/EricGu/archive/2009/03/26/262019.html</guid><wfw:comment>http://www.blogjava.net/EricGu/comments/262019.html</wfw:comment><comments>http://www.blogjava.net/EricGu/archive/2009/03/26/262019.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/EricGu/comments/commentRss/262019.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/EricGu/services/trackbacks/262019.html</trackback:ping><description><![CDATA[<div align="left"><font face="宋体">在使用</font><font face="arial">InelliJ IDEA</font><font face="宋体">的过程中，通过查找资料以及一些自己的摸索，发现这个众多</font><font face="arial">Java</font><font face="宋体">程序员喜欢的</font><font face="arial">IDE</font><font face="宋体">里有许多值得一提的小窍门，如果能熟练的将它们应用于实际开发过程中，相信它会大大节省你的开发时间，而且随之而来的还会有那么一点点成就感：）</font><font face="arial">Try it</font><font face="宋体">！</font></div>
<div align="left"><font face="arial">1</font><font face="宋体">、写代码时用</font><strong><font face="arial">Alt-Insert</font></strong><font face="宋体">（</font><strong><font face="arial">Code|Generate&#8230;</font></strong><font face="宋体">）可以创建类里面任何字段的</font><font face="arial">getter</font><font face="宋体">与</font><font face="arial">setter</font><font face="宋体">方法。</font></div>
<div align="left"><font face="arial"></font></div>
<div align="left"><font face="arial">2</font><font face="宋体">、右键点击断点标记（在文本的左边栏里）激活速查菜单，你可以快速设置</font><strong><font face="arial">enable/disable</font></strong><font face="宋体">断点或者条件它的属性。</font></div>
<div align="left"><img onclick="window.open('http://cnmick.blogchina.com/inc/image001.gif');" src="http://cnmick.blogchina.com/inc/image001.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></div>
<div align="left"><font face="arial">3</font><font face="宋体">、</font><font face="arial">CodeCompletion</font><font face="宋体">（代码完成）属性里的一个特殊的变量是，激活</font><strong><font face="arial">Ctrl-Alt-Space</font></strong><font face="宋体">可以完成在或不在当前文件里的类名。如果类没有引入则</font><font face="arial">import</font><font face="宋体">标志会自动创建。</font></div>
<div align="left"><img onclick="window.open('http://cnmick.blogchina.com/inc/image002.gif');" src="http://cnmick.blogchina.com/inc/image002.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></div>
<div align="left"><font face="arial">4</font><font face="宋体">、使用</font><strong><font face="arial">Ctrl-Shift-V</font></strong><font face="宋体">快捷键可以将最近使用的剪贴板内容选择插入到文本。使用时系统会弹出一个含有剪贴内容的对话框，从中你可以选择你要粘贴的部分。</font></div>
<div align="left"><font face="arial">5</font><font face="宋体">、利用</font><font face="arial">CodeCompletion</font><font face="宋体">（代码完成）属性可以快速地在代码中完成各种不同地语句，方法是先键入一个类名地前几个字母然后再用</font><strong><font face="arial">Ctrl-Space</font></strong><font face="宋体">完成全称。如果有多个选项，它们会列在速查列表里。</font></div>
<div align="left"><font face="arial">&nbsp;<img onclick="window.open('http://cnmick.blogchina.com/inc/image003.gif');" src="http://cnmick.blogchina.com/inc/image003.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">6</font><font face="宋体">、用</font><strong><font face="arial">Ctrl-/</font></strong><font face="宋体">与</font><strong><font face="arial">Ctrl-Shift-/</font></strong><font face="宋体">来注释</font><font face="arial">/</font><font face="宋体">反注释代码行与代码块。</font></div>
<div align="left"><font face="arial">-/</font><font face="宋体">用单行注释标记（&#8220;</font><strong><font face="arial">//&#8230;</font></strong><font face="宋体">&#8221;）来注释</font><font face="arial">/</font><font face="宋体">反注释当前行或者选择地代码块。而</font><font face="arial">Ctrl-Shift-/</font><font face="宋体">则可以用块注释标记（&#8220;</font><strong><font face="arial">/<span style="display: none"> V;}HGn </span>&nbsp;<br />
&#8230;<span style="display: none"> dy/?S GW </span>&nbsp;<br />
/</font></strong><font face="宋体">&#8221;）把所选块包围起来。要反注释一个代码块就在块中任何一个地方按</font><font face="arial">Ctrl-Shift-/</font><font face="宋体">即可。</font></div>
<div align="left"><font face="arial">7</font><font face="宋体">、按</font><strong><font face="arial">Alt-Q</font></strong><font face="宋体">（</font><strong><font face="arial">View|Context Info</font></strong><font face="宋体">）可以不需要移动代码就能查看当前方法地声明。连续按两次会显示当前所编辑的类名。</font></div>
<div align="left"><font face="arial">8</font><font face="宋体">、使用</font><strong><font face="arial">Refactor|Copy Class&#8230;</font></strong><font face="宋体">可以创建一个所选择的类的&#8220;副本&#8221;。这一点很有用，比如，在你想要创建一个大部分内容都和已存在类相同的类时。</font></div>
<div align="left"><font face="arial">9</font><font face="宋体">、在编辑器里</font><strong><font face="arial">Ctrl-D</font></strong><font face="宋体">可以复制选择的块或者没有所选块是的当前行。</font></div>
<div align="left"><font face="arial">10</font><font face="宋体">、</font><strong><font face="arial">Ctrl-W</font></strong><font face="宋体">（选择字）在编辑器里的功能是先选择脱字符处的单词，然后选择源代码的扩展区域。举例来说，先选择一个方法名，然后是调用这个方法的表达式，然后是整个语句，然后包容块，等等。</font></div>
<div align="left"><font face="arial">11</font><font face="宋体">、如果你不想让指示事件细节的&#8220;亮球&#8221;图标在编辑器上显示，通过按</font><strong><font face="arial">Alt-Enter</font></strong><font face="宋体">组合键打开所有事件列表然后用鼠标点击它就可以把这个事件文本附件的亮球置成非活动状态。</font></div>
<div align="left"><font face="宋体">这样以后就不会有指示特殊事件的亮球出现了，但是你仍然可以用</font><strong><font face="arial">Alt-Enter</font></strong><font face="宋体">快捷键使用它。</font></div>
<div align="left"><font face="arial">12</font><font face="宋体">、在使用</font><font face="arial">CodeCompletion</font><font face="宋体">时，可以用逗点（</font><font face="arial">.</font><font face="宋体">）字符，逗号（，）分号（；），空格和其它字符输入弹出列表里的当前高亮部分。选择的名字会随着输入的字符自动输入到编辑器里。</font></div>
<div align="left"><font face="arial">13</font><font face="宋体">、在任何工具窗口里使用</font><strong><font face="arial">Escape</font></strong><font face="宋体">键都可以把焦点移到编辑器上。</font></div>
<div align="left"><strong><font face="arial">Shift-Escape</font></strong><font face="宋体">不仅可以把焦点移到编辑器上而且还可以隐藏当前（或最后活动的）工具窗口。</font></div>
<div align="left"><font face="arial">F12</font><font face="宋体">键把焦点从编辑器移到最近使用的工具窗口。</font></div>
<div align="left"><font face="arial">14</font><font face="宋体">、在调试程序时查看任何表达式值的一个容易的方法就是在编辑器中选择文本（可以按几次</font><strong><font face="arial">Ctrl-W</font></strong><font face="宋体">组合键更有效地执行这个操作）然后按</font><font face="arial">Alt-F8</font><font face="宋体">。</font></div>
<div align="left"><font face="arial">15</font><font face="宋体">、要打开编辑器脱字符处使用的类或者方法</font><font face="arial">Java</font><font face="宋体">文档的浏览器，就按</font><strong><font face="arial">Shift-F1</font></strong><font face="宋体">（右键菜单的</font><strong><font face="arial">External JavaDoc</font></strong><font face="宋体">）。</font></div>
<div align="left"><font face="宋体">要使用这个功能须要把加入浏览器的路径，在&#8220;</font><strong><font face="arial">General</font></strong><font face="宋体">&#8221;选项中设置（</font><strong><font face="arial">Options | IDE Settings</font></strong><font face="宋体">），另外还要把创建的</font><font face="arial">Java</font><font face="宋体">文档加入到工程中（</font><strong><font face="arial">File | Project Properties</font></strong><font face="宋体">）。</font></div>
<div align="left"><font face="arial">16</font><font face="宋体">、用</font><strong><font face="arial">Ctrl-F12</font></strong><font face="宋体">（</font><strong><font face="arial">View | File Structure Popup</font></strong><font face="宋体">）键你可以在当前编辑的文件中快速导航。</font></div>
<div align="left"><font face="宋体">这时它会显示当前类的成员列表。选中一个要导航的元素然后按</font><font face="arial">Enter</font><font face="宋体">键或</font><font face="arial">F4</font><font face="宋体">键。要轻松地定位到列表中的一个条目，只需键入它的名字即可。</font></div>
<div align="left"><font face="arial">17</font><font face="宋体">、在代码中把光标置于标记符或者它的检查点上再按</font><strong><font face="arial">Alt-F7</font></strong><font face="宋体">（右键菜单中的</font><strong><font face="arial">Find Usages&#8230;</font></strong><font face="宋体">）会很快地查找到在整个工程中使用地某一个类、方法或者变量的位置。</font></div>
<div align="left"><font face="arial">18</font><font face="宋体">、按</font><strong><font face="arial">Ctrl-N</font></strong><font face="宋体">（</font><strong><font face="arial">Go to | Class&#8230;</font></strong><font face="宋体">）再键入类的名字可以快速地在编辑器里打开任何一个类。从显示出来的下拉列表里选择类。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image004.gif');" src="http://cnmick.blogchina.com/inc/image004.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="宋体">同样的方法你可以通过使用</font><strong><font face="arial">Ctrl-Shift-N</font></strong><font face="宋体">（</font><strong><font face="arial">Go to | File&#8230;</font></strong><font face="宋体">）打开工程中的非</font><font face="arial">Java</font><font face="宋体">文件。</font></div>
<div align="left"><font face="arial">19</font><font face="宋体">、要导航代码中一些地方使用到的类、方法或者变量的声明，把光标放在查看项上再按</font><font face="arial">Ctrl-B</font><font face="宋体">即可。也可以通过按</font><font face="arial">Ctrl</font><font face="宋体">键的同时在查看点上单击鼠标键调转到声明处。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image005.gif');" src="http://cnmick.blogchina.com/inc/image005.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">20</font><font face="宋体">、把光标放到查看点上再按</font><strong><font face="arial">Ctrl-Alt-B</font></strong><font face="宋体">可以导航到一个抽象方法的实现代码。</font></div>
<div align="left"><font face="arial">21</font><font face="宋体">、要看一个所选择的类的继承层次，按</font><strong><font face="arial">Ctrl-H</font></strong><font face="宋体">（</font><strong><font face="arial">Browse Type Hierarchy</font></strong><font face="宋体">）即可。也可以激活编辑器中的继承关系视图查看当前编辑类的继承关系。</font></div>
<div align="left"><font face="arial"></font></div>
<div align="left">　<img onclick="window.open('http://cnmick.blogchina.com/inc/image006.gif');" src="http://cnmick.blogchina.com/inc/image006.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></div>
<div align="left"><font face="arial">22</font><font face="宋体">、使用</font><strong><font face="arial">Ctrl-Shift-F7</font></strong><font face="宋体">（</font><strong><font face="arial">Search | Highlight Usages in File</font></strong><font face="宋体">）可以快速高亮显示当前文件中某一变量的使用地方。按</font><font face="arial">Escape</font><font face="宋体">清除高亮显示。</font></div>
<div align="left"><font face="arial">23</font><font face="宋体">、用</font><strong><font face="arial">Alt-F3</font></strong><font face="宋体">（</font><strong><font face="arial">Search | Incremental Search</font></strong><font face="宋体">）在编辑器中实现快速查查找功能。</font></div>
<div align="left"><font face="宋体">在&#8220;</font><strong><font face="arial">Search for:</font></strong><font face="宋体">&#8221;提示工具里输入字符，使用箭头键朝前和朝后搜索。按</font><strong><font face="arial">Escape</font></strong><font face="宋体">退出。</font></div>
<div align="left"><font face="arial">24</font><font face="宋体">、按</font><strong><font face="arial">Ctrl-J</font></strong><font face="宋体">组合键来执行一些你记不起来的</font><strong><font face="arial">Live Template</font></strong><font face="宋体">缩写。比如，键&#8220;</font><strong><font face="arial">it</font></strong><font face="宋体">&#8221;然后按</font><strong><font face="arial">Ctrl-J</font></strong><font face="宋体">看看有什么发生。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image007.gif');" src="http://cnmick.blogchina.com/inc/image007.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">25</font><font face="宋体">、</font><strong><font face="arial">Introduce Variable</font></strong><font face="宋体">整合帮助你简化代码中复杂的声明。举个例子，在下面的代码片断里，在代码中选择一个表达式：</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image008.gif');" src="http://cnmick.blogchina.com/inc/image008.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial"></font><font face="宋体">然后按</font><strong><font face="arial">Ctrl-Alt-V</font></strong><font face="宋体">（</font><strong><font face="arial">Refactor | Introduce Variable</font></strong><font face="宋体">）就会出现下面的结果：</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image009.gif');" src="http://cnmick.blogchina.com/inc/image009.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">26</font><font face="宋体">、</font><strong><font face="arial">Ctrl-Shift-J</font></strong><font face="宋体">快捷键把两行合成一行并把不必要的空格去掉以匹配你的代码格式。</font></div>
<div align="left"><font face="arial">27</font><font face="宋体">、</font><strong><font face="arial">Ctrl-Shift-Backspace</font></strong><font face="宋体">（</font><strong><font face="arial">Go to | Last Edit Location</font></strong><font face="宋体">）让你调转到代码中所做改变的最后一个地方。</font></div>
<div align="left"><font face="宋体">多按几次</font><strong><font face="arial">Ctrl-Shift-Backspace</font></strong><font face="宋体">查看更深的修改历史。</font></div>
<div align="left"><font face="arial">28</font><font face="宋体">、用</font><strong><font face="arial">Tools | Reformat Code&#8230;</font></strong><font face="宋体">根据你的代码样式参考（查看</font><strong><font face="arial">Options | IDE Setting | Code Style</font></strong><font face="宋体">）格式化代码。</font></div>
<div align="left"><font face="宋体">使用</font><strong><font face="arial">Tools | Optimize Imports&#8230;</font></strong><font face="宋体">可以根据设置（查看</font><strong><font face="arial">Options | IDE Setting | Code Style | Imports</font></strong><font face="宋体">）自动&#8220;优化&#8221;</font><strong><font face="arial">imports</font></strong><font face="宋体">（清除无用的</font><strong><font face="arial">imports</font></strong><font face="宋体">等）。</font></div>
<div align="left"><font face="arial">29</font><font face="宋体">、使用</font><font face="arial">IDEA</font><font face="宋体">的</font><strong><font face="arial">Live Templates | Live Templates</font></strong><font face="宋体">让你在眨眼间创建许多典型代码。比如，在一个方法里键入</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image010.gif');" src="http://cnmick.blogchina.com/inc/image010.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="宋体">再按</font><strong><font face="arial">Tab</font></strong><font face="宋体">键看有什么事情发生了。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image011.gif');" src="http://cnmick.blogchina.com/inc/image011.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="宋体">用</font><font face="arial">Tab</font><font face="宋体">键在不同的模板域内移动。查看</font><strong><font face="arial">Options | Live Templates</font></strong><font face="宋体">获取更多的细节。</font></div>
<div align="left"><font face="arial">30</font><font face="宋体">、要查看一个文件中修改的本地历史，激活右键菜单里的</font><strong><font face="arial">Local VCS | Show History&#8230;</font></strong><font face="宋体">。也许你可以导航不同的文件版本，看看它们的不同之处再回滚到以前的任何一个版本吧。</font></div>
<div align="left"><font face="宋体">使用同样的右键菜单条目还可以看到一个目录里修改的历史。有了这个特性你就不会丢失任何代码了。</font></div>
<div align="left"><font face="arial">31</font><font face="宋体">、如果要了解主菜单里每一个条目的用途，把鼠标指针移到菜单条目上再应用程序框架的底部的状态栏里就会显示它们的一些简短描述，也许会对你有帮助。</font></div>
<div align="left"><font face="arial">32</font><font face="宋体">、要在编辑器里显示方法间的分隔线，打开</font><strong><font face="arial">Options | IDE Settings | Editor</font></strong><font face="宋体">，选中&#8220;</font><strong><font face="arial">Show method separators</font></strong><font face="宋体">&#8221;检查盒（</font><strong><font face="arial">checkbox</font></strong><font face="宋体">）。</font></div>
<div align="left"><font face="arial">33</font><font face="宋体">、<strong>用</strong></font><strong><font face="arial">Alt-Up</font></strong><font face="宋体">和</font><strong><font face="arial">Alt-Down</font></strong><font face="宋体">键可以在编辑器里不同的方法之间快速移动。</font></div>
<div align="left"><font face="arial">34</font><font face="宋体">、用</font><strong><font face="arial">F2/Shift-F2</font></strong><font face="宋体">键在高亮显示的语法错误间跳转。</font></div>
<div align="left"><font face="宋体">用</font><strong><font face="arial">Ctrl-Alt-Down/Ctrl-Alt-Up</font></strong><font face="宋体">快捷键则可以在编译器错误信息或者查找操作结果间跳转。</font></div>
<div align="left"><font face="arial">35</font><font face="宋体">、通过按</font><strong><font face="arial">Ctrl-O</font></strong><font face="宋体">（</font><strong><font face="arial">Code | Override Methods&#8230;</font></strong><font face="宋体">）可以很容易地重载基本类地方法。</font></div>
<div align="left"><font face="宋体">要完成当前类</font><strong><font face="arial">implements</font></strong><font face="宋体">的（或者抽象基本类的）接口的方法，就使用</font><strong><font face="arial">Ctrl-I</font></strong><font face="宋体">（</font><strong><font face="arial">Code | Implement Methods&#8230;</font></strong><font face="宋体">）。</font></div>
<div align="left"><font face="arial">36</font><font face="宋体">、如果光标置于一个方法调用的括号间，按</font><strong><font face="arial">Ctrl-P</font></strong><font face="宋体">会显示一个可用参数的列表。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image012.gif');" src="http://cnmick.blogchina.com/inc/image012.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">37</font><font face="宋体">、要快速查看编辑器脱字符处使用的类或方法的</font><font face="arial">Java</font><font face="宋体">文档，按</font><strong><font face="arial">Ctrl-Q</font></strong><font face="宋体">（在弹出菜单的</font><strong><font face="arial">Show Quick JavaDoc</font></strong><font face="宋体">里）即可。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image013.gif');" src="http://cnmick.blogchina.com/inc/image013.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">38</font><font face="宋体">、像</font><strong><font face="arial">Ctrl-Q</font></strong><font face="宋体">（</font><strong><font face="arial">Show Quick JavaDoc</font></strong><font face="宋体">显示简洁</font><font face="arial">Java</font><font face="宋体">文档），</font><strong><font face="arial">Ctrl-P</font></strong><font face="宋体">（</font><strong><font face="arial">Show Parameter Info</font></strong><font face="宋体">显示参数信息），</font><strong><font face="arial">Ctrl-B</font></strong><font face="宋体">（</font><strong><font face="arial">Go to Declaration</font></strong><font face="宋体">跳转到声明），</font><strong><font face="arial">Shift-F1</font></strong><font face="宋体">（</font><strong><font face="arial">External JavaDoc</font></strong><font face="宋体">外部</font><font face="arial">Java</font><font face="宋体">文档）以及其它一些快捷键不仅可以在编辑器里使用，也可以应用在代码完成右键列表里。</font></div>
<div align="left"><font face="arial">39</font><font face="宋体">、</font><strong><font face="arial">Ctrl-E</font></strong><font face="宋体">（</font><strong><font face="arial">View | Recent Files</font></strong><font face="宋体">）弹出最近访问的文件右键列表。选中文件按</font><strong><font face="arial">Enter</font></strong><font face="宋体">键打开。</font></div>
<div align="left"><font face="arial">40</font><font face="宋体">、在</font><font face="arial">IDEA</font><font face="宋体">中可以很容易地对你的类，方法以及变量进行重命名并在所有使用到它们的地方自动更正。</font></div>
<div align="left"><font face="宋体">试一下，把编辑器脱字符置于任何一个变量名字上然后按</font><strong><font face="arial">Shift-F6</font></strong><font face="宋体">（</font><strong><font face="arial">Refactor | Rename&#8230;</font></strong><font face="宋体">）。在对话框里键入要显示地新名字再按</font><font face="arial">Enter</font><font face="宋体">。你会浏览到使用这个变量地所有地方然后按&#8220;</font><strong><font face="arial">Do Refactor</font></strong><font face="宋体">&#8221;按钮结束重命名操作。</font></div>
<div align="left"><font face="arial">41</font><font face="宋体">、要在任何视图（</font><strong><font face="arial">Project View</font></strong><font face="宋体">工程视图，</font><strong><font face="arial">Structure View</font></strong><font face="宋体">结构视图或者其它视图）里快速</font></div>
<div align="left"><font face="宋体">选择当前编辑地部分（类，文件，方法或者字段），按</font><strong><font face="arial">Alt-F1</font></strong><font face="宋体">（</font><strong><font face="arial">View | Select in&#8230;</font></strong><font face="宋体">）。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image014.gif');" src="http://cnmick.blogchina.com/inc/image014.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">42</font><font face="宋体">、在&#8220;</font><strong><font face="arial">new</font></strong><font face="宋体">&#8221;字符后实例化一个已知类型对象时也许你会用到</font><font face="arial">SmartType</font><font face="宋体">代码完成这个特性。比如，键入</font></div>
<div align="left"><font face="arial">&nbsp;<img onclick="window.open('http://cnmick.blogchina.com/inc/image015.gif');" src="http://cnmick.blogchina.com/inc/image015.gif" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="宋体">再按</font><strong><font face="arial">Ctrl-Shift-Space</font></strong><font face="宋体">：</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image016.gif');" src="http://cnmick.blogchina.com/inc/image016.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">43</font><font face="宋体">、通过使用</font><font face="arial">SmartType</font><font face="宋体">代码完成，在</font><font face="arial">IDEA</font><font face="宋体">中创建接口的整个匿名</font><strong><font face="arial">implementation</font></strong><font face="宋体">也是非常容易的，比如，对于一些</font><font face="arial">listener</font><font face="宋体">（监听器），可以键入</font></div>
<div align="left"><font face="arial">&nbsp; Component component;</font></div>
<div align="left"><font face="arial">&nbsp; component.addMouseListener(</font></div>
<div align="left"><font face="arial">&nbsp;&nbsp;&nbsp; new w w <strong><em><font color="#005555">&lt;caret is here&gt;</font></em></strong>&nbsp;</font></div>
<div align="left"><font face="arial">&nbsp; );</font></div>
<div align="left"><font face="宋体">然后再按</font><strong><font face="arial">Ctrl-Shift-Space</font></strong><font face="宋体">看看有什么发生了。</font></div>
<div align="left"><font face="arial">44</font><font face="宋体">、在你需要设置一个已知类型的表达式的值时用</font><font face="arial">SmartType</font><font face="宋体">代码完成也很有帮助。比如，键入</font></div>
<div align="left"><font face="arial">String s = (<strong><em><font color="#005555">&lt;caret is here&gt;</font></em></strong>&nbsp;</font></div>
<div align="left"><font face="宋体">再按</font><strong><font face="arial">Ctrl-Shift-Space</font></strong><font face="宋体">看看会有什么出现。</font></div>
<div align="left"><font face="arial">45</font><font face="宋体">、在所有视图里都提供了速查功能：在树里只需键入字符就可以快速定位到一个条目。</font></div>
<div align="left"><font face="arial">46</font><font face="宋体">、当你想用代码片断捕捉异常时，在编辑器里选中这个片断，按</font><strong><font face="arial">Ctrl-Alt-T</font></strong><font face="宋体">（</font><strong><font face="arial">Code | Surround with&#8230;</font></strong><font face="宋体">）然后选择</font><font face="arial">&#8220;<strong>try/catch</strong>&#8221;</font><font face="宋体">。它会自动产生代码片断中抛出的所有异常的捕捉块。在</font><strong><font face="arial">Options | File Templates | Code tab</font></strong><font face="宋体">中你还可以自己定制产生捕捉块的模板。</font></div>
<div align="left"><font face="宋体">用列表中的其它项可以包围别的一些结构。</font></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image017.gif');" height="200" src="http://cnmick.blogchina.com/inc/image017.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="arial">47</font><font face="宋体">、在使用代码完成时，用</font><font face="arial">Tab</font><font face="宋体">键可以输入弹出列表里的高亮显示部分。</font></div>
<div align="left"><font face="宋体">不像用</font><strong><font face="arial">Enter</font></strong><font face="宋体">键接受输入，这个选中的名字会覆盖掉脱字符右边名字的其它部分。这一点在用一个方法或者变量名替换另一个时特别有用。</font></div>
<div align="left"><font face="arial">48</font><font face="宋体">、在声明一个变量时代码完成特性会给你显示一个建议名。比如，开始键入</font><font face="arial">&#8220;private FileOutputStream&#8221;</font><font face="宋体">然后按</font><strong><font face="arial">Ctrl-Space</font></strong></div>
<div align="left"><font face="arial"><img onclick="window.open('http://cnmick.blogchina.com/inc/image018.gif');" src="http://cnmick.blogchina.com/inc/image018.gif" width="300" onload="if(this.width  alt="" />'300')this.width='300';if(this.height>'200')this.height='200';" border=0></font></div>
<div align="left"><font face="宋体">在</font><strong><font face="arial">Options | IDE Setting | Code Style</font></strong><font face="宋体">中还可以为本地变量，参数，实例及静态字段定制名字。<br />
<br />
</font></div>
 <img src ="http://www.blogjava.net/EricGu/aggbug/262019.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/EricGu/" target="_blank">Eric Gu</a> 2009-03-26 09:33 <a href="http://www.blogjava.net/EricGu/archive/2009/03/26/262019.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>