<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
  <channel>
    <title>brainstorm</title>
    <description>养老中。</description>
    <link>http://brainstorm.javaeye.com</link>
    <language>UTF-8</language>
    <copyright>Copyright 2003-2008, JavaEye.com</copyright>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <generator>JavaEye - 做最棒的软件开发交流社区</generator>
      <item>
        <title>Java Container学习笔记</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/124848" style="color:red;">http://brainstorm.javaeye.com/blog/124848</a>&nbsp;
          发表时间: 2007年09月18日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p>Java Container的分类图见<strong>附件1,</strong>简化分类图见<strong>附件2</strong>。</p>
<p><strong>Container分类简介：</strong></p>
<p>&nbsp;&nbsp;&nbsp; Container包括Collection和Map两种分类，其中Collection用来保存单个的Objects，Map以Key-Value的形式来保存Objects。Collection包括List和Set两种，List接口包括两个基本的实现类ArrayList和LinkedList。ArrayList允许随机的快速访问其中元素，但是Insert和Remove速度较慢；LinkedList访问其中元素的速度较慢，但是Insert和Remove相对于ArrayList来说较快。Set接口不允许其中有相等的元素(List允许duplicate elements)，其包括两个基本的实现类HashSet和TreeSet。HashTable支持快速的查找元素（要求元素支持hashCode方法），其中的元素随机保存；TreeSet以一定的顺序保存元素，它实现SortedSet接口，均可以返回Comparator接口来确定其排序算法，元素通过实现Comparable接口来确定其间的顺序。Map接口以key-value的形式保存元素，Map中的key都是unique的，其包括两个实现类HashMap和TreeMap。HashMap是HashTable的替代品，它提供定时间的插入和查找元素；TreeMap中的key sets是以一定的顺序保存的，这和TreeSet是类似的，也可以返回Comparator接口来确定其key set的排序算法。</p>
<p><strong>HashCode的作用：</strong></p>
<p>HashCode是为了在HashSet里面更快的查找元素。HashSet在填充元素时候，会对object的hashcode进行一些归类处理，生成一系列的buckets(一般是能够控制在一定范围的)。然后把bucket作为数组的索引，每个数组元素保存一个List，将所有在此bucket内的元素填充入该List当中。当查找元素时候，只需要先根据元素的hashcode找到相应的索引，然后从索引指向的List当中依次查找该元素即可。设计hashcode需要考虑其的聚焦性，尽量减少hashcode的聚焦性，减少多个hashcode指向一个索引的情况，可以更好的提高HashSet的性能。</p>
<p><strong>Iterator的说明：</strong></p>
<p>Iterator是为Contanier提供了一个按照顺序依次取出Container元素的类。Iterator隐藏了取出元素机制和低层结构，程序员不需要知道低层到底是List还是Set还是Map，就可以从其中按照顺序取出元素。也正是因为如此，Iterator只提供了按单方向顺序取出元素。</p>
<p><strong>工具类的说明：</strong></p>
<p>Collections封装了一些常用的方法。包括对List的排序，取其中最大最小元素等等...</p>
<p><strong>如何根据需求选择不同的实现类：</strong></p>
<p>首先，Hashtable，Vector，Stack已经不被推荐使用，保留它们只是为了使遗留系统的代码不被破坏。所以这三个类可以忽略考虑。当使用List的时候，最好的方法是把ArrayList作为Default选择，当发现需要大量的Insertions和removals需求时改换LinkedList；使用Set的时候，如果需要有顺序的查找和取出元素，那么选择TreeSet，否则选择HashSet；使用Map的时候，HashMap用来更快的查找元素，而TreeMap允许按照一定顺序来根据key查找元素。</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/124848#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Tue, 18 Sep 2007 00:53:00 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/124848</link>
        <guid>http://brainstorm.javaeye.com/blog/124848</guid>
      </item>
      <item>
        <title>紫光输入法和SWT的冲突问题(典型：Eclipse异常退出)</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/123070" style="color:red;">http://brainstorm.javaeye.com/blog/123070</a>&nbsp;
          发表时间: 2007年09月12日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p>前段时间使用RadRails时候经常无故死机，RadRails使用的是Eclipse内核，我上网找了很久，但是解决方法基本都是改eclipse.ini配置，无论我怎么修改也无法解决此问题。后来用DbVisualizer（一个基于java的DB GUI）时候也出现这种异常退出问题，无异都是jvm terminated, code=xxx。我一开始认为是jvm的问题，遂分别换了1.4.2,1.5,1.6分别测试，结果问题没有解决。实在没办法，开始研究log。</p>
<p>下面是一个log的前半部分。</p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span># &nbsp;&nbsp;</span></span> </li>
    <li class=""><span>#&nbsp;An&nbsp;unexpected&nbsp;error&nbsp;has&nbsp;been&nbsp;detected&nbsp;by&nbsp;Java&nbsp;Runtime&nbsp;Environment: &nbsp;&nbsp;</span> </li>
    <li class="alt"><span># &nbsp;&nbsp;</span> </li>
    <li class=""><span>#&nbsp;&nbsp;EXCEPTION_ACCESS_VIOLATION&nbsp;(</span><span class="number">0xc0000005</span><span>)&nbsp;at&nbsp;pc=</span><span class="number">0x03f75517</span><span>,&nbsp;pid=</span><span class="number">1780</span><span>,&nbsp;tid=</span><span class="number">1996</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span># &nbsp;&nbsp;</span> </li>
    <li class=""><span>#&nbsp;Java&nbsp;VM:&nbsp;Java&nbsp;HotSpot(TM)&nbsp;Client&nbsp;VM&nbsp;(</span><span class="number">1.6</span><span>.</span><span class="number">0</span><span>-b105&nbsp;mixed&nbsp;mode,&nbsp;sharing) &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>#&nbsp;Problematic&nbsp;frame: &nbsp;&nbsp;</span> </li>
    <li class=""><span>#&nbsp;C&nbsp;&nbsp;[UNISPIM6.IME+</span><span class="number">0x5517</span><span>] &nbsp;&nbsp;</span> </li>
    <li class="alt"><span># &nbsp;&nbsp;</span> </li>
    <li class=""><span>#&nbsp;If&nbsp;you&nbsp;would&nbsp;like&nbsp;to&nbsp;submit&nbsp;a&nbsp;bug&nbsp;report,&nbsp;please&nbsp;visit: &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>#&nbsp;&nbsp;&nbsp;http:</span><span class="comment">//java.sun.com/webapps/bugreport/crash.jsp </span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span>#&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>大家注意第8行的那个UNISPIM6.IME,你们猜猜那是什么东西，google一下，发现是紫光输入法......。我流汗了，随即删除了紫光输入法。然后使用Eclipse超过2小时，有异常的时候一般都10-15分钟就会退出，结果一切正常。然后我去DbVisualizer下面查看了log，结果上面的那段又重复了。所以我认为紫光输入法肯定会对java中SWT的输入造成些问题。(DbVisualizer和Eclipse都是基于SWT的)。</p>
<p>上面一段是我根据log确定的，因为出异常的在DbVisualizer里面是和AWT相关的类，在Eclipse里面是和SWT相关的类。</p>
<p>那么，我只好在这里发个广告，使用java程序就不要使用紫光输入法了(紫光请原谅我，我见异思迁了)，使用google的好了。</p>
<p>这里我放个秘籍给大家哈，大家去下下傲游Maxthon2.0的版本，然后安装紫光输入法。Okey,点击Ctrl-F，是不是出来一个查找的小窗口，然后大家把鼠标移动到别处点下，是不是发现查找窗口不见了，收藏的那个窗口也是一样。所以，我估计可能Maxthon使用了部分SWT的技术。我在3台电脑上测试出有此问题。我的紫光版本记不得了，反正是2个月前下的，估计现在的可能已经解决了吧。</p>
<p>希望这篇文章能够帮助有同样问题的朋友解决疑惑，也凭此悼念我浪费的时间。</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/123070#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Wed, 12 Sep 2007 02:01:18 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/123070</link>
        <guid>http://brainstorm.javaeye.com/blog/123070</guid>
      </item>
      <item>
        <title>Hibernate学习笔记-Transaction Isolation</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/121450" style="color:red;">http://brainstorm.javaeye.com/blog/121450</a>&nbsp;
          发表时间: 2007年09月07日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p>Transaction如果不隔绝，则在多个transactions访问数据库时容易产生如下问题：</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>1，Lost update</strong> - 两个transactions同时更新同一行，由于第2个transaction的abort，造成2个更新都失去。这一般发生在系统没有对transaction进行隔绝。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>2，Dirty read</strong> - 一个transaction正在读取另一个还没有commited的transaction对数据库做的改变。如果第2个transaction roll back,那么第一个transaction读取的信息就是不同步的。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>3，Unrepeatable read</strong> - 一个transaction对数据库中同一行数据读取了2遍，但是读取出来的数据却不同。这可能发生的情况是在这两次读取的间隔另一个transaction对该行做了更新。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>4，Second lost updates problem</strong> - 这种问题是Unrepeatable read的一种特例。当2个transactions同时读取一行，其中一个对该行做了更新并且commited,此时另外一transaction可能也会对此行做更新。那么第一个transaction做的改变就失效了。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>5，Phantom read</strong> - 一个transaction执行了2次同一个query，但是第2次query读出的结果集合有第一个不存在的行。这发生在在两次query执行之间另一个transaction新增了新行。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px">为了解决以上问题，引入了Transaction Isolation的概念，并且对Isolation做了分级。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px">ANSI SQL和JTA定义的Isolation Level是一致的，包括以下四种Level：</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>1，Read uncommitted</strong> - 允许Dirty Read但是不允许Lost update。即一个transaction在更新数据库的一行时，别的Transaction不能对其做写操作，只能做读操作。这是通过排它写锁实现的。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>2，Read committed</strong> - 允许Unrepeatable reads但是不允许Dirty reads。对一行做读操作的transactions不会block其它访问改行的transaction，但是一个没有committed的对该行进行写操作的transaction会block掉其它的transaction（包括读操作的transaction）。这是通过排它写锁和瞬时的共享读锁实现的。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>3，Repeatable Read</strong> - 在此level下，只有Phantom read可能发生。当一个transaction对数据库进行读操作时候，它会block掉其它全部的transactions（不包括只读的transactions），而一个对数据库进行写操作的transaction就会block掉其它全部的transactions。这是通过排它写锁和共享读锁实现的。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px"><strong>4，Serializable</strong> - 这是最严格的Isolation level。他让全部的transactions以线性的方式依次执行。这是通过排它锁实现的。</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px">Hibernate中设置隔绝类型的方法：</p>
<p dir="ltr" style="MARGIN-RIGHT: 0px">在cfg里面修改<font face="Arial">hibernate.connection.isolation属性。相关可选属性：</font><font face="Arial"><br />
1&mdash;Read uncommitted isolation<br />
2&mdash;Read committed isolation<br />
4&mdash;Repeatable read isolation<br />
8&mdash;Serializable isolation</font></p>
<p dir="ltr" style="MARGIN-RIGHT: 0px">&nbsp;</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/121450#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Fri, 07 Sep 2007 03:01:00 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/121450</link>
        <guid>http://brainstorm.javaeye.com/blog/121450</guid>
      </item>
      <item>
        <title>Hibernate学习笔记 - Persistence Manager查找objects的几种方式。</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/120803" style="color:red;">http://brainstorm.javaeye.com/blog/120803</a>&nbsp;
          发表时间: 2007年09月06日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <strong>1，</strong>最简单的方法就是通过database identifier。通过ID来从数据库中调取相应的行来生成object。下面的代码就是通过user id来查找相应的object。
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span>User&nbsp;user&nbsp;=&nbsp;(User)&nbsp;session.get(User.</span><span class="keyword">class</span><span>,&nbsp;userID);&nbsp;&nbsp;</span></span></li>
</ol>
</div>
<p><strong>2，</strong>通过HQL(Hibernate Query Language)来查找。HQL是类似于SQL的一种数据库语言，但是其只支持select功能，对update,insert,delete不支持。因为在Hibernate中，数据库的操作是交给Persitence Manager来控制的。下面是一个例子。</p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span>Query&nbsp;q&nbsp;=&nbsp;session.createQuery(</span><span class="string">&quot;from&nbsp;User&nbsp;u&nbsp;where&nbsp;u.firstname&nbsp;=&nbsp;:fname&quot;</span><span>); &nbsp;&nbsp;</span></span></li>
    <li class=""><span>q.setString(</span><span class="string">&quot;fname&quot;</span><span>,&nbsp;</span><span class="string">&quot;Max&quot;</span><span>); &nbsp;&nbsp;</span></li>
    <li class="alt"><span>List&nbsp;result&nbsp;=&nbsp;q.list();&nbsp;&nbsp;</span></li>
</ol>
</div>
<p><strong>3，</strong>通过Hibernate query by criteria(QBC)API来实现。QBC使用OO的思想来查找objects，所以没有HQL那么功能强大，而且想对来说更难于理解。下面是一个例子。</p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span>Criteria&nbsp;criteria&nbsp;=&nbsp;session.createCriteria(User.</span><span class="keyword">class</span><span>); &nbsp;&nbsp;</span></span></li>
    <li class=""><span>criteria.add(&nbsp;Expression.like(</span><span class="string">&quot;firstname&quot;</span><span>,&nbsp;</span><span class="string">&quot;Max&quot;</span><span>)&nbsp;); &nbsp;&nbsp;</span></li>
    <li class="alt"><span>List&nbsp;result&nbsp;=&nbsp;criteria.list();&nbsp;&nbsp;</span></li>
</ol>
</div>
<p>Expression类提供静态方法来返回被过滤后的集合。</p>
<p><strong>4，</strong>Query by example(QBE)是QBC的一种特殊表现形式，它要求程序提供一个供参考的例子来做为查找的根据。下面是一个例子。</p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span>User&nbsp;exampleUser&nbsp;=&nbsp;</span><span class="keyword">new</span><span>&nbsp;User(); &nbsp;&nbsp;</span></span></li>
    <li class=""><span>exampleUser.setFirstname(</span><span class="string">&quot;Max&quot;</span><span>); &nbsp;&nbsp;</span></li>
    <li class="alt"><span>Criteria&nbsp;criteria&nbsp;=&nbsp;session.createCriteria(User.</span><span class="keyword">class</span><span>); &nbsp;&nbsp;</span></li>
    <li class=""><span>criteria.add(&nbsp;Example.create(exampleUser)&nbsp;); &nbsp;&nbsp;</span></li>
    <li class="alt"><span>List&nbsp;result&nbsp;=&nbsp;criteria.list();&nbsp;&nbsp;</span></li>
</ol>
</div>
<p>程序建立了一个示范的exampleUser，其firstname为Max，然后通过此示范来查找符合要求的users。</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/120803#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Thu, 06 Sep 2007 02:14:00 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/120803</link>
        <guid>http://brainstorm.javaeye.com/blog/120803</guid>
      </item>
      <item>
        <title>Hibernate学习笔记 - Object的三种状态</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/120796" style="color:red;">http://brainstorm.javaeye.com/blog/120796</a>&nbsp;
          发表时间: 2007年09月06日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p>objects在hibernate中的生命周期中存在3种状态:transient, persistent, detached。附件1描述的即是hibernate application中objects的生命周期。</p>
<p>通过new操作符生成的object是transient object，此时的object还没有和数据库中的任何数据关联，所以一旦没有被引用，就会被jvm垃圾收集。一旦通过Hibernate 的Persistence manager执行了save()方法或者被其他已经存在的Persistent objects引用，那么object的状态就会从transient转为persistent。</p>
<p>Persistent objects是包含在transactions中的，它们的状态是通过transactions来控制的，&nbsp; Persistent objects是和数据库中的表对应的，所以表示主键的属性不会为空，也就是说每一个persistent object都会有一个匹配的database identity，除非是通过new产生的新的transient object,此时object的database identity是空的，如果在transaction中对该object执行save()方法，那么在transaction成功结束的时候该object会在数据库中新增一条对应的记录，其它已经存在的persistent objects会相应的更新数据库中的相应行。</p>
<p>当Hibernate中的Persistence Manager执行close()方法，也就是persistence Manager放弃对persistent objects的控制，那么persistent objects的状态就转为detached objects。这些detached objects可以在未来被新的persistence manager重新控制并使用。这种将object从transaction转向表现层然后又重新包含于新的Transaction的实现是Hibernate的一个卖点。</p>
<p>在objects存在的三种状态中，处于persistent状态中object的比较是通过该object的database identity来确定的，所以这里需要override equals()来实现。其它状态中的objects就可以简单的通过java的equality来判断即可。</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/120796#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Thu, 06 Sep 2007 01:47:00 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/120796</link>
        <guid>http://brainstorm.javaeye.com/blog/120796</guid>
      </item>
      <item>
        <title>一些Java的英文面试题(转)</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/120795" style="color:red;">http://brainstorm.javaeye.com/blog/120795</a>&nbsp;
          发表时间: 2007年09月06日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p><strong>以前找得一些题目，出处忘记了。大家有兴趣看看吧。</strong></p>
<p><strong>内容包括了core java, struts, jsp &amp; servlet以及一些general的问题。</strong></p>
<p><strong></strong></p>
<p>Question: <br />
<br />
What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class?(donated in June 2005)<br />
<br />
Answer: <br />
<br />
Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future. <br />
<br />
Question: <br />
<br />
An application needs to load a library before it starts to run, how to code?<br />
<br />
Answer: <br />
<br />
One option is to use a static block to load a library before anything is called. For example,<br />
<br />
class Test { <br />
static {<br />
System.loadLibrary(&quot;path-to-library-file&quot;);<br />
}<br />
....<br />
}<br />
<br />
When you call new Test(), the static block will be called first before any initialization happens. Note that the static block position may matter. <br />
<br />
<br />
Question: <br />
<br />
What is a platform? <br />
<br />
Answer: <br />
<br />
A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000 and XP, Linux, Solaris, and MacOS. <br />
<br />
Question: <br />
<br />
What is the main difference between Java platform and other platforms? <br />
<br />
Answer: <br />
<br />
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. <br />
<br />
The Java platform has two components: <br />
<br />
1. The Java Virtual Machine (Java VM) <br />
2. The Java Application Programming Interface (Java API) <br />
<br />
Question: <br />
<br />
What is the Java Virtual Machine? <br />
<br />
Answer: <br />
<br />
The Java Virtual Machine is a software that can be ported onto various hardware-based platforms. <br />
<br />
Question: <br />
<br />
What is the Java API? <br />
<br />
Answer: <br />
<br />
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. <br />
<br />
Question: <br />
<br />
What is the package? <br />
<br />
Answer: <br />
<br />
The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages. <br />
<br />
Question: <br />
<br />
What is native code? <br />
<br />
Answer: <br />
<br />
The native code is code that after you compile it, the compiled code runs on a specific hardware platform. <br />
<br />
Question: <br />
<br />
Can main() method be overloaded? <br />
<br />
Answer: <br />
<br />
Yes. the main() method is a special method for a program entry. You can overload main() method in any ways. But if you change the signature of the main method, the entry point for the program will be gone. <br />
<br />
Question: <br />
<br />
What is the serialization? <br />
<br />
Answer: <br />
<br />
The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage. <br />
<br />
Question: <br />
<br />
How to make a class or a bean serializable? <br />
<br />
Answer: <br />
<br />
By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable. <br />
<br />
Question: <br />
<br />
What is J2EE? <br />
<br />
Answer: <br />
<br />
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. <br />
<br />
Question: <br />
<br />
What are the four types of J2EE modules? <br />
<br />
Answer: <br />
<br />
1. Application client module <br />
2. Web module <br />
3. Enterprise JavaBeans module <br />
4. Resource adapter module <br />
<br />
<br />
Question: <br />
<br />
What are the differences between Ear, Jar and War files? Under what circumstances should we use each one? (donated in April, 2005)<br />
<br />
Answer: <br />
<br />
There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.<br />
<br />
--Jar files (files with a .jar extension) are intended to hold generic libraries of Java classes, resources, auxiliary files, etc. <br />
--War files (files with a .war extension) are intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context. <br />
--Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web applications. <br />
<br />
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc. <br />
<br />
Question: <br />
<br />
What two protocols are used in Java RMI technology? <br />
<br />
Answer: <br />
<br />
Java Object Serialization and HTTP. The Object Serialization protocol is used to marshal call and return data. The HTTP protocol is used to &quot;POST&quot; a remote method invocation and obtain return data when circumstances warrant. <br />
<br />
<br />
Question: <br />
Explain for 10 to 15 minutes a technology or product that you are familiar with.(donated in April,2005) <br />
Answer: <br />
This is to test the person's communication skill and technical skill. If you are really comfortable, start with a public domain technology like Struts or JUnit. If not, sometimes it is better to explain the product that you worked with rather than read about or studied.<br />
<br />
Question: <br />
Tell me about yourself? <br />
Answer: <br />
The first is focusing on the needs of the organization. The second is focusing on the needs of the people within that organization. Don't talk so much about strong points about yourself because your resume has already brought you at the interview site. <br />
<br />
Question: <br />
Why should we hire you? <br />
Answer: <br />
Summarize your experiences: &quot;With five years' experience working in this industry and my proven record of saving the company money, I could make a big difference in your company. I'm confident I would be a great addition to your team.&quot; <br />
<br />
<br />
Question: <br />
Why do you want to work here? <br />
Answer: <br />
The interviewer is listening for an answer that indicates you've given this some thought and are not sending out resumes just because there is an opening. For example, &quot;I've selected key companies whose mission statements are in line with my values, where I know I could be excited about what the company does, and this company is very high on my list of desirable choices.&quot; <br />
<br />
Question: <br />
What are your goals? <br />
Answer: <br />
Sometimes it's best to talk about short-term and intermediate goals rather than locking yourself into the distant future. For example, &quot;My immediate goal is to get a job in a growth-oriented company. My long-term goal will depend on where the company goes. I hope to eventually grow into a position of responsibility.&quot; <br />
<br />
<br />
Question: <br />
Why did you leave (are you leaving) your job? <br />
Answer: <br />
If you're unemployed, state your reason for leaving in a positive context: &quot;I managed to survive two rounds of corporate downsizing, but the third round was a 20 percent reduction in the workforce, which included me.&quot; <br />
<br />
If you are employed, focus on what you want in your next job: &quot;After two years, I made the decision to look for a company that is team-focused, where I can add my experience.&quot; <br />
<br />
<br />
Question: <br />
When were you most satisfied in your job? <br />
Answer: <br />
The interviewer wants to know what motivates you. If you can relate an example of a job or project when you were excited, the interviewer will get an idea of your preferences. &quot;I was very satisfied in my last job, because I worked directly with the customers and their problems; that is an important part of the job for me.&quot; <br />
<br />
Question: <br />
What can you do for us that other candidates can't? or <br />
What makes you unique? <br />
Answer: <br />
This will take an assessment of your experiences, skills and traits. Summarize concisely: &quot;I have a unique combination of strong technical skills, and the ability to build strong customer relationships. This allows me to use my knowledge and break down information to be more user-friendly.&quot; <br />
<br />
Question: <br />
What are three positive things your last boss would say about you? <br />
Answer: <br />
It's time to pull out your old performance appraisals and boss's quotes. This is a great way to brag about yourself through someone else's words: &quot;My boss has told me that I am the best designer he has ever had. He knows he can rely on me, and he likes my sense of humor.&quot; <br />
<br />
Question: <br />
What salary are you seeking? <br />
Answer: <br />
It is to your advantage if the employer tells you the range first. Prepare by knowing the going rate in your area, and your bottom line or walk-away point. One possible answer would be: &quot;I am sure when the time comes, we can agree on a reasonable amount. In what range do you typically pay someone with my background?&quot; <br />
<br />
Question: <br />
<br />
What is ActionServlet?(donated in Nov.2005)<br />
<br />
Answer: <br />
<br />
ActionServlet is the Command part of the MVC implementation and is the core of the Struts Framework. ActionServlet creates and uses Action, an ActionForm, and ActionForward. The struts-config.xml file configures the Command. During the creation of the Web project, Action and ActionForm are extended to solve the specific problem space. The file struts-config.xml instructs ActionServlet on how to use the extended classes. <br />
<br />
Question: <br />
What is Jakarta Struts Framework? (donated in Nov. 2005) <br />
Answer: <br />
Jakarta Struts is an open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java <br />
<br />
<br />
Question: <br />
<br />
What is Struts? <br />
<br />
Answer: <br />
<br />
Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between. <br />
<br />
<br />
Question: <br />
<br />
How is the MVC design pattern used in Struts framework? <br />
<br />
Answer: <br />
<br />
In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. <br />
<br />
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSP page and presentation components; Model --- System state and a business logic JavaBeans. <br />
<br />
<br />
Question: <br />
<br />
What are the core classes of Struts? <br />
<br />
Answer: <br />
<br />
Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs. <br />
Question: <br />
<br />
What is the design role played by Struts? <br />
<br />
Answer: <br />
<br />
The role played by Structs is controller in Model/View/Controller(MVC) style. The View is played by JSP and Model is played by JDBC or generic data source classes. The Struts controller is a set of programmable components that allow developers to define exactly how the application interacts with the user. <br />
<br />
<br />
Question: <br />
<br />
How Struts control data flow? <br />
<br />
Answer: <br />
<br />
Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep control-flow decisions out of presentation layer. <br />
<br />
Question: <br />
<br />
What configuration files are used in Struts? <br />
<br />
Answer: <br />
<br />
--ApplicationResourcesl.properties <br />
--struts-config.xml <br />
<br />
These two files are used to bridge the gap between the Controller and the Model. <br />
<br />
Question: <br />
<br />
What helpers in the form of JSP pages are provided in Struts framework? <br />
<br />
Answer: <br />
<br />
--struts-html.tld <br />
--struts-bean.tld <br />
--struts-logic.tld <br />
<br />
Question: <br />
<br />
What is Servlet?<br />
<br />
Answer: <br />
<br />
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm. <br />
<br />
Question: <br />
<br />
Why is Servlet so popular?<br />
<br />
Answer: <br />
<br />
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server. <br />
Question: <br />
<br />
What is servlet container?<br />
<br />
Answer: <br />
<br />
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle. <br />
Question: <br />
<br />
When a client request is sent to the servlet container, how does the container choose which servlet to invoke? <br />
<br />
Answer: <br />
<br />
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response. <br />
Question: <br />
<br />
If a servlet is not properly initialized, what exception may be thrown?<br />
<br />
Answer: <br />
<br />
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException. <br />
<br />
Question: <br />
<br />
Given the request path below, which are context path, servlet path and path info?<br />
<br />
Answer: <br />
<br />
/bookstore/education/index.html<br />
<br />
context path: /bookstore<br />
servlet path: /education<br />
path info: /index.html <br />
<br />
Question: <br />
<br />
What is filter? Can filter be used as request or response?<br />
<br />
Answer: <br />
<br />
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. <br />
Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource. <br />
Question: <br />
<br />
When using servlets to build the HTML, you build a DOCTYPE line, why do you do that? <br />
<br />
Answer: <br />
<br />
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors. <br />
<br />
Question: <br />
<br />
How do you call a bean method from a Javascript onclick handler? (donated in Oct,2005) <br />
<br />
Answer: <br />
<br />
This is a trick question. JavaScript onclick handler is usually handled on the client side and a bean method is handled on the server side. It is not possible to call a bean method from a Javascript onclick handler directly. Explain it why or ask back to clarify this question. <br />
<br />
Question: <br />
<br />
What is a JSP and what is it used for? <br />
<br />
Answer: <br />
<br />
Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. <br />
Question: <br />
<br />
What is JSP technology? <br />
<br />
Answer: <br />
<br />
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language. <br />
Question: <br />
<br />
What is JSP page? <br />
<br />
Answer: <br />
<br />
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content. <br />
Question: <br />
<br />
What are the implicit objects? <br />
<br />
Answer: <br />
<br />
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:<br />
<br />
--request <br />
--response <br />
--pageContext <br />
--session <br />
--application <br />
--out <br />
--config <br />
--page <br />
--exception <br />
<br />
Q: What is the difference between an Interface and an Abstract class? <br />
<br />
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.<br />
. <br />
TOP <br />
<br />
Q: What is the purpose of garbage collection in Java, and when is it used?<br />
<br />
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. <br />
TOP <br />
<br />
Q: Describe synchronization in respect to multithreading.<br />
<br />
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. <br />
TOP <br />
<br />
Q: Explain different way of using thread? <br />
<br />
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help. <br />
TOP <br />
<br />
Q: What are pass by reference and passby value? <br />
<br />
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. <br />
TOP <br />
<br />
Q: What is HashMap and Map?<br />
<br />
A: Map is Interface and Hashmap is class that implements that. <br />
TOP <br />
<br />
Q: Difference between HashMap and HashTable?<br />
<br />
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized. <br />
TOP <br />
<br />
Q: Difference between Vector and ArrayList?<br />
<br />
A: Vector is synchronized whereas arraylist is not. <br />
TOP <br />
<br />
Q: Difference between Swing and Awt?<br />
<br />
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT. <br />
TOP <br />
<br />
Q: What is the difference between a constructor and a method? <br />
<br />
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.<br />
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. <br />
TOP <br />
<br />
Q: What is an Iterator?<br />
<br />
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator. <br />
TOP <br />
<br />
Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.<br />
<br />
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)<br />
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.<br />
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.<br />
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package. <br />
TOP <br />
<br />
Q: What is an abstract class?<br />
<br />
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.<br />
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. <br />
TOP <br />
<br />
Q: What is static in java?<br />
<br />
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass. <br />
TOP <br />
<br />
Q: What is final?<br />
<br />
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). <br />
Q: What if the main method is declared as private?<br />
<br />
A: The program compiles properly but at runtime it will give &quot;Main method not public.&quot; message. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What if the static modifier is removed from the signature of the main method?<br />
<br />
A: Program compiles. But at runtime throws an error &quot;NoSuchMethodError&quot;. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What if I write static public void instead of public static void?<br />
<br />
A: Program compiles and runs properly. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What if I do not provide the String array as the argument to the method?<br />
<br />
A: Program compiles but throws a runtime error &quot;NoSuchMethodError&quot;. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the first argument of the String array in main method?<br />
<br />
A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?<br />
<br />
A: It is empty. But not null. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: How can one prove that the array is not null but empty using one line of code?<br />
<br />
A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What environment variables do I need to set on my machine in order to be able to run Java programs?<br />
<br />
A: CLASSPATH and PATH are the two variables. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can an application have multiple classes having main method?<br />
<br />
A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can I have multiple main methods in the same class?<br />
<br />
A: No the program fails to compile. The compiler says that the main method is already defined in the class. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Do I need to import java.lang package any time? Why ?<br />
<br />
A: No. It is by default loaded internally by the JVM. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?<br />
<br />
A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What are Checked and UnChecked Exception?<br />
<br />
A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.<br />
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method&middot;<br />
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the<br />
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method&middot; Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. <br />
TOP <br />
<br />
Q: What is Overriding?<br />
<br />
A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.<br />
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private. <br />
TOP <br />
<br />
Q: What are different types of inner classes?<br />
<br />
A: Nested top-level classes, Member classes, Local classes, Anonymous classes<br />
<br />
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.<br />
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.<br />
<br />
Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.<br />
<br />
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a<br />
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.<br />
<br />
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.<br />
<br />
TOP <br />
Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?<br />
<br />
A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol<br />
symbol : class ABCD<br />
location: package io<br />
import java.io.ABCD; <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?<br />
<br />
A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the difference between declaring a variable and defining a variable?<br />
<br />
A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.<br />
e.g String s; is just a declaration while String s = new String (&quot;abcd&quot;); Or String s = &quot;abcd&quot;; are both definitions. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the default value of an object reference declared as an instance variable?<br />
<br />
A: null unless we define it explicitly. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can a top level class be private or protected?<br />
<br />
A: No. A top level class can not be private or protected. It can have either &quot;public&quot; or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the &quot;modifier private is not allowed here&quot;. This means that a top level class can not be private. Same is the case with protected. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What type of parameter passing does Java support?<br />
<br />
A: In Java the arguments are always passed by value . <br />
[ Update from Eki and Jyothish Venu] TOP <br />
<br />
Q: Primitive data types are passed by reference or pass by value?<br />
<br />
A: Primitive data types are passed by value. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Objects are passed by value or by reference?<br />
<br />
A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object . <br />
[ Update from Eki and Jyothish Venu] TOP <br />
<br />
Q: What is serialization?<br />
<br />
A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: How do I serialize an object to a file?<br />
<br />
A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Which methods of Serializable interface should I implement?<br />
<br />
A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: How can I customize the seralization process? i.e. how can one have a control over the serialization process?<br />
<br />
A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the common usage of serialization?<br />
<br />
A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is Externalizable interface?<br />
<br />
A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: When you serialize an object, what happens to the object references included in the object?<br />
<br />
A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What one should take care of while serializing the object?<br />
<br />
A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What happens to the static fields of a class during serialization? <br />
<br />
A: There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are<br />
1. Serialization ignores static fields, because they are not part of ay particular state state.<br />
2. Base class fields are only hendled if the base class itself is serializable.<br />
3. Transient fields. <br />
<br />
Q: Does Java provide any construct to find out the size of an object?<br />
<br />
A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Give a simplest way to find out the time a method takes for execution without using any profiling tool?<br />
<br />
A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution. <br />
To put it in code...<br />
<br />
long start = System.currentTimeMillis ();<br />
method ();<br />
long end = System.currentTimeMillis ();<br />
<br />
System.out.println (&quot;Time taken for execution is &quot; + (end - start));<br />
<br />
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.<br />
<br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What are wrapper classes?<br />
<br />
A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Why do we need wrapper classes?<br />
<br />
A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What are checked exceptions?<br />
<br />
A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What are runtime exceptions?<br />
<br />
A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the difference between error and an exception?<br />
<br />
A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: How to create custom exceptions?<br />
<br />
A: Your class should extend class Exception, or some more specific type thereof. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: If I want an object of my class to be thrown as an exception object, what should I do?<br />
<br />
A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?<br />
<br />
A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: How does an exception permeate through the code?<br />
<br />
A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What are the different ways to handle exceptions?<br />
<br />
A: There are two ways to handle exceptions, <br />
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and <br />
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the basic difference between the 2 approaches to exception handling.<br />
1&gt; try catch block and <br />
2&gt; specifying the candidate exceptions in the throws clause?<br />
When should you use which approach?<br />
<br />
A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Is it necessary that each try block must be followed by a catch block?<br />
<br />
A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: If I write return at the end of the try block, will the finally block still execute?<br />
<br />
A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?<br />
<br />
A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. <br />
Q: How are Observer and Observable used?<br />
<br />
A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. <br />
[Received from Venkateswara Manam] TOP <br />
<br />
Q: What is synchronization and why is it important?<br />
<br />
A: With respect to multithreading, synchronization is the capability to control<br />
the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: How does Java handle integer overflows and underflows?<br />
<br />
A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: Does garbage collection guarantee that a program will not run out of memory?<br />
<br />
A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection<br />
. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What is the difference between preemptive scheduling and time slicing?<br />
<br />
A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: When a thread is created and started, what is its initial state?<br />
<br />
A: A thread is in the ready state after it has been created and started. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What is the purpose of finalization?<br />
<br />
A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What is the Locale class?<br />
<br />
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What is the difference between a while statement and a do statement?<br />
<br />
A: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What is the difference between static and non-static variables?<br />
<br />
A: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: How are this() and super() used with constructors?<br />
<br />
A: This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What are synchronized methods and synchronized statements?<br />
<br />
A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What is daemon thread and which method is used to create the daemon thread?<br />
<br />
A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread. <br />
[ Received from Shipra Kamra] TOP <br />
<br />
Q: Can applets communicate with each other?<br />
<br />
A: At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable. <br />
<br />
An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members. <br />
<br />
It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial. <br />
[ Received from Krishna Kumar ] TOP <br />
<br />
Q: What are the steps in the JDBC connection?<br />
<br />
A: While making a JDBC connection we go through the following steps : <br />
<br />
Step 1 : Register the database driver by using : <br />
Class.forName(\&quot; driver classs for that specific database\&quot; );<br />
<br />
Step 2 : Now create a database connection using :<br />
<br />
Connection con = DriverManager.getConnection(url,username,password);<br />
<br />
Step 3: Now Create a query using :<br />
<br />
Statement stmt = Connection.Statement(\&quot;select * from TABLE NAME\&quot;);<br />
<br />
Step 4 : Exceute the query :<br />
<br />
stmt.exceuteUpdate();<br />
<br />
<br />
<br />
[ Received from Shri Prakash Kunwar] TOP <br />
<br />
Q: How does a try statement determine which catch clause should be used to handle an exception?<br />
<br />
A: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.<br />
<br />
<br />
Q: Can an unreachable object become reachable again?<br />
<br />
A: An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. <br />
[Received from P Rajesh] TOP <br />
<br />
Q: What method must be implemented by all threads?<br />
<br />
A: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.<br />
<br />
[ Received from P Rajesh] TOP <br />
<br />
Q: What are synchronized methods and synchronized statements?<br />
<br />
A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.<br />
<br />
[ Received from P Rajesh] TOP <br />
<br />
Q: What is Externalizable? <br />
<br />
A: Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in) <br />
[ Received from Venkateswara Manam] TOP <br />
<br />
Q: What modifiers are allowed for methods in an Interface?<br />
<br />
A: Only public and abstract modifiers are allowed for methods in interfaces. <br />
<br />
[ Received from P Rajesh] TOP <br />
<br />
Q: What are some alternatives to inheritance?<br />
<br />
A: Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).<br />
<br />
[ Received from P Rajesh] TOP <br />
<br />
Q: What does it mean that a method or field is &quot;static&quot;? <br />
<br />
A: Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. <br />
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class. <br />
<br />
<br />
<br />
[ Received from P Rajesh] TOP <br />
<br />
Q: What is the difference between preemptive scheduling and time slicing?<br />
<br />
A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. <br />
<br />
[ Received from P Rajesh] TOP <br />
<br />
Q: What is the catch or declare rule for method declarations? <br />
<br />
A: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. <br />
<br />
Q: Is Empty .java file a valid source file?<br />
<br />
A: Yes, an empty .java file is a perfectly valid source file. <br />
[Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can a .java file contain more than one java classes?<br />
<br />
A: Yes, a .java file contain more than one java classes, provided at the most one of them is a public class. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Is String a primitive data type in Java?<br />
<br />
A: No String is not a primitive data type in Java, even though it is one of the most extensively used object. Strings in Java are instances of String class defined in java.lang package. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Is main a keyword in Java? <br />
<br />
A: No, main is not a keyword in Java. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Is next a keyword in Java?<br />
<br />
A: No, next is not a keyword. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Is delete a keyword in Java?<br />
<br />
A: No, delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Is exit a keyword in Java? <br />
<br />
A: No. To exit a program explicitly you use exit method in System object. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What happens if you dont initialize an instance variable of any of the primitive types in Java?<br />
<br />
A: Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0, a boolean will be initialized to false. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What will be the initial value of an object reference which is defined as an instance variable? <br />
<br />
A: The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What are the different scopes for Java variables? <br />
<br />
A: The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.<br />
1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.<br />
2. Local : - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.<br />
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What is the default value of the local variables? <br />
<br />
A: The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain abt the local varaible not being initilized.. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: How many objects are created in the following piece of code?<br />
MyClass c1, c2, c3;<br />
c1 = new MyClass ();<br />
c3 = new MyClass ();<br />
<br />
<br />
A: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can a public class MyClass be defined in a source file named YourClass.java? <br />
<br />
A: No the source file name, if it contains a public class, must be the same as the public class name itself with a .java extension. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: Can main method be declared final? <br />
<br />
A: Yes, the main method can be declared final, in addition to being public static. <br />
[ Received fromSandesh Sadhale] TOP <br />
<br />
Q: What will be the output of the following statement?<br />
System.out.println (&quot;1&quot; + 3); <br />
<br />
A: It will print 13. <br />
[ Received from Sandesh Sadhale] TOP <br />
<br />
Q: What will be the default values of all the elements of an array defined as an instance variable? <br />
<br />
A: If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.</p>
<p>&nbsp;</p>
<p>Questions start the minute the interview does, and to show that you are an exceptional candidate, you need to be prepared to answer not only the typical questions, but also the unexpected. You can expect questions regarding your qualifications, your academic preparation, career interests, experience, and ones that assess your personality. <br />
1. Tell me about yourself<br />
The most often asked question in interviews. You need to have a short statement prepared in your mind. Be careful that it does not sound rehearsed. Limit it to work-related items unless instructed otherwise. Talk about things you have done and jobs you have held that relate to the position you are interviewing for. Start with the item farthest back and work up to the present. <br />
<br />
2. Why did you leave your last job?<br />
Stay positive regardless of the circumstances. Never refer to a major problem with management and never speak ill of supervisors, co-workers or the organization. If you do, you will be the one looking bad. Keep smiling and talk about leaving for a positive reason such as an opportunity, a chance to do something special or other forward-looking reasons. <br />
<br />
3. What experience do you have in this field?<br />
Speak about specifics that relate to the position you are applying for. If you do not have specific experience, get as close as you can. <br />
<br />
4. Do you consider yourself successful?<br />
You should always answer yes and briefly explain why. A good explanation is that you have set goals, and you have met some and are on track to achieve the others. <br />
<br />
5. What do co-workers say about you?<br />
Be prepared with a quote or two from co-workers. Either a specific statement or a paraphrase will work. <br />
<br />
6. What do you know about this organization?<br />
This question is one reason to do some research on the organization before the interview. Find out where they have been and where they are going. What are the current issues and who are the major players? <br />
<br />
7. What have you done to improve your knowledge in the last year?<br />
Try to include improvement activities that relate to the job. A wide variety of activities can be mentioned as positive self-improvement. Have some good ones handy to mention. <br />
<br />
8. Are you applying for other jobs?<br />
Be honest but do not spend a lot of time in this area. Keep the focus on this job and what you can do for this organization. Anything else is a distraction. <br />
<br />
9. Why do you want to work for this organization?<br />
This may take some thought and certainly, should be based on the research you have done on the organization. Sincerity is extremely important here and will easily be sensed. Relate it to your long-term career goals. <br />
<br />
10. Do you know anyone who works for us?<br />
Be aware of the policy on relatives working for the organization. This can affect your answer even though they asked about friends not relatives. Be careful to mention a friend only if they are well thought of. <br />
<br />
11. What kind of salary do you need?<br />
A loaded question. A nasty little game that you will probably lose if you answer first. So, do not answer it. Instead, say something like, That's a tough question. Can you tell me the range for this position? In most cases, the interviewer, taken off guard, will tell you. If not, say that it can depend on the details of the job. Then give a wide range. <br />
<br />
12. Are you a team player?<br />
You are, of course, a team player. Be sure to have examples ready. Specifics that show you often perform for the good of the team rather than for yourself are good evidence of your team attitude. Do not brag, just say it in a matter-of-fact tone. This is a key point. <br />
<br />
13. How long would you expect to work for us if hired?<br />
Specifics here are not good. Something like this should work: I'd like it to be a long time. Or As long as we both feel I'm doing a good job. <br />
<br />
14. Have you ever had to fire anyone? How did you feel about that?<br />
This is serious. Do not make light of it or in any way seem like you like to fire people. At the same time, you will do it when it is the right thing to do. When it comes to the organization versus the individual who has created a harmful situation, you will protect the organization. Remember firing is not the same as layoff or reduction in force. <br />
<br />
15. What is your philosophy towards work?<br />
The interviewer is not looking for a long or flowery dissertation here. Do you have strong feelings that the job gets done? Yes. That's the type of answer that works best here. Short and positive, showing a benefit to the organization. <br />
<br />
16. If you had enough money to retire right now, would you?<br />
Answer yes if you wou</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/120795#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Thu, 06 Sep 2007 01:13:28 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/120795</link>
        <guid>http://brainstorm.javaeye.com/blog/120795</guid>
      </item>
      <item>
        <title>REST介绍</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/119963" style="color:red;">http://brainstorm.javaeye.com/blog/119963</a>&nbsp;
          发表时间: 2007年09月04日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <h2 goog_ds_charindex="1" align="left"><font size="2">给软件世界写的稿子，9月见刊，已经9月，可以发布在blog上了。</font></h2>
<h2 goog_ds_charindex="1" align="center">REST介绍</h2>
<p goog_ds_charindex="9" align="left">&nbsp;&nbsp;&nbsp;&nbsp; REST架构风格是全新的针对Web应用的开发风格，是当今世界最成功的互联网超媒体分布式系统架构，它使得人们真正理解了Http协议本来面貌。随着REST架构成为主流技术，一种全新的互联网网络应用开发的思维方式开始流行。</p>
<p goog_ds_charindex="124" align="left">&nbsp;</p>
<p goog_ds_charindex="125" align="left">&nbsp;&nbsp;&nbsp;&nbsp; <strong goog_ds_charindex="131">REST是什么</strong></p>
<p goog_ds_charindex="141" align="left">&nbsp;&nbsp;&nbsp;&nbsp; REST是英文Representational State Transfer的缩写，中文翻译为&ldquo;表述性状态转移&rdquo;，他是由Roy Thomas&nbsp;Fielding博士在他的论文 《Architectural Styles and the Design of Network-based Software Architectures》中提出的一个术语。REST本身只是为分布式超媒体系统设计的一种架构风格，而不是标准。</p>
<p goog_ds_charindex="354" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 基于Web的架构，实际上就是各种规范的集合，这些规范共同组成了Web架构。比如Http协议，比如客户端服务器模式，这些都是规范。每当我们在原有规范的基础上增加新的规范，就会形成新的架构。而REST正是这样一种架构，他结合了一系列的规范，而形成了一种新的基于Web的架构风格。</p>
<p goog_ds_charindex="498" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 传统的Web应用大都是B/S架构，它包括了如下一些规范&nbsp;。</p>
<p goog_ds_charindex="534" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 客户－服务器</p>
<ul goog_ds_charindex="547">
    <li goog_ds_charindex="548">
    <div goog_ds_charindex="549" align="left">这种规范的提出，改善了用户接口跨多个平台的可移植性，并且通过简化服务器组件，改善了系统的可伸缩性。最为关键的是通过分离用户接口和数据存储这两个关注点，使得不同用户终端享受相同数据成为了可能。</div>
    </li>
</ul>
<p goog_ds_charindex="648" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 无状态性</p>
<ul goog_ds_charindex="659">
    <li goog_ds_charindex="660">
    <div goog_ds_charindex="661" align="left">无状态性是在客户－服务器约束的基础上添加的又一层规范。他要求通信必须在本质上是无状态的，即从客户到服务器的每个request都必须包含理解该request所必须的所有信息。这个规范改善了系统的可见性（无状态性使得客户端和服务器端不必保存对方的详细信息，服务器只需要处理当前request，而不必了解所有的request历史），可靠性（无状态性减少了服务器从局部错误中恢复的任务量），可伸缩性（无状态性使得服务器端可以很容易的释放资源，因为服务器端不必在多个request中保存状态）。同时，这种规范的缺点也是显而易见得，由于不能将状态数据保存在服务器上的共享上下文中，因此增加了在一系列request中发送重复数据的开销,严重的降低了效率。</div>
    </li>
</ul>
<p goog_ds_charindex="985" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 缓存</p>
<ul goog_ds_charindex="994">
    <li goog_ds_charindex="995">
    <div goog_ds_charindex="996" align="left">为了改善无状态性带来的网络的低效性，我们填加了缓存约束。缓存约束允许隐式或显式地标记一个response中的数据，这样就赋予了客户端缓存response数据的功能，这样就可以为以后的request共用缓存的数据，部分或全部的消除一部分交互，增加了网络的效率。但是用于客户端缓存了信息，也就同时增加了客户端与服务器数据不一致的可能，从而降低了可靠性。</div>
    </li>
</ul>
<p goog_ds_charindex="1174" align="left">&nbsp;&nbsp;&nbsp;&nbsp; B/S架构的优点是其部署非常方便，但在用户体验方面却不是很理想。为了改善这种情况，我们引入了REST。</p>
<p goog_ds_charindex="1232" align="left">&nbsp;&nbsp;&nbsp;&nbsp; REST在原有的架构上增加了三个新规范：统一接口，分层系统和按需代码。</p>
<p goog_ds_charindex="1274" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 统一接口</p>
<ul goog_ds_charindex="1285">
    <li goog_ds_charindex="1286">
    <div goog_ds_charindex="1287" align="left">REST架构风格的核心特征就是强调组件之间有一个统一的接口，这表现在REST世界里，网络上所有的事物都被抽象为资源，而REST就是通过通用的链接器接口对资源进行操作。这样设计的好处是保证系统提供的服务都是解耦的，极大的简化了系统，从而改善了系统的交互性和可重用性。并且REST针对Web的常见情况做了优化，使得REST接口被设计为可以高效的转移大粒度的超媒体数据，这也就导致了REST接口对其它的架构并不是最优的。</div>
    </li>
</ul>
<p goog_ds_charindex="1498" align="left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;分层系统</p>
<ul goog_ds_charindex="1509">
    <li goog_ds_charindex="1510">
    <div goog_ds_charindex="1511" align="left">分层系统规则的加入提高了各种层次之间的独立性，为整个系统的复杂性设置了边界，通过封装遗留的服务，使新的服务器免受遗留客户端的影响，这也就提高了系统的可伸缩性。</div>
    </li>
</ul>
<p goog_ds_charindex="1594" align="left">&nbsp;&nbsp;&nbsp;&nbsp; 按需代码</p>
<ul goog_ds_charindex="1605">
    <li goog_ds_charindex="1606">
    <div goog_ds_charindex="1607" align="left">REST允许对客户端功能进行扩展。比如，通过下载并执行applet或脚本形式的代码，来扩展客户端功能。但这在改善系统可扩展性的同时，也降低了可见性。所以它只是REST的一个可选的约束。</div>
    </li>
</ul>
<p goog_ds_charindex="1703" align="left">&nbsp;</p>
<p goog_ds_charindex="1704" align="left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong goog_ds_charindex="1710">REST的设计准则</strong></p>
<p goog_ds_charindex="1722" align="left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;REST架构是针对Web应用而设计的，其目的是为了降低开发的复杂性，提高系统的可伸缩性。REST提出了如下设计准则：</p>
<ol goog_ds_charindex="1787">
    <ol goog_ds_charindex="1788">
        <li goog_ds_charindex="1789">
        <div goog_ds_charindex="1790" align="left">网络上的所有事物都被抽象为资源（resource）；</div>
        </li>
        <li goog_ds_charindex="1819">
        <div goog_ds_charindex="1820" align="left">每个资源对应一个唯一的资源标识符（resource identifier）； </div>
        </li>
        <li goog_ds_charindex="1862">
        <div goog_ds_charindex="1863" align="left">通过通用的连接器接口（generic connector interface）对资源进行操作；</div>
        </li>
        <li goog_ds_charindex="1913">
        <div goog_ds_charindex="1914" align="left">对资源的各种操作不会改变资源标识符；</div>
        </li>
        <li goog_ds_charindex="1935">
        <div goog_ds_charindex="1936" align="left">所有的操作都是无状态的（stateless）。</div>
        </li>
    </ol>
</ol>
<p goog_ds_charindex="1964" align="left">&nbsp;&nbsp;&nbsp;&nbsp; REST中的资源所指的不是数据，而是数据和表现形式的组合，比如&ldquo;最新访问的10位会员&rdquo;和&ldquo;最活跃的10为会员&rdquo;在数据上可能有重叠或者完全相同，而由于他们的表现形式不同，所以被归为不同的资源，这也就是为什么REST的全名是Representational State Transfer的原因。资源标识符就是URI(Uniform Resource Identifier)，不管是图片，Word还是视频文件，甚至只是一种虚拟的服务，也不管你是xml格式,txt文件格式还是其它文件格式，全部通过URI对资源进行唯一的标识。</p>
<p goog_ds_charindex="2230" align="left">&nbsp;&nbsp;&nbsp;&nbsp; REST是基于Http协议的，任何对资源的操作行为都是通过Http协议来实现。以往的Web开发大多数用的都是Http协议中的GET和POST方法，对其他方法很少使用，这实际上是因为对Http协议认识片面的理解造成的。Http不仅仅是一个简单的运载数据的协议，而是一个具有丰富内涵的网络软件的协议。他不仅仅能对互联网资源进行唯一定位，而且还能告诉我们如何对该资源进行操作。Http把对一个资源的操作限制在4个方法以内：GET,POST,PUT和DELETE，这正是对资源CRUD操作的实现。由于资源和URI是一一对应的，执行这些操作的时候URI是没有变化的，这和以往的Web开发有很大的区别。正由于这一点，极大的简化了Web开发，也使得URI可以被设计成更为直观的反映资源的结构，这种URI的设计被称作RESTful的URI。这位开发人员引入了一种新的思维方式：通过URL来设计系统结构。当然了，这种设计方式对一些特定情况也是不适用的，也就是说不是所有的URI都可以RESTful的。</p>
<p goog_ds_charindex="2678" align="left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;REST之所以可以提高系统的可伸缩性，就是因为它要求所有的操作都是无状态的。由于没有了上下文(Context)的约束，做分布式和集群的时候就更为简单，也可以让系统更为有效的利用缓冲池(Pool）。并且由于服务器端不需要记录客户端的一系列访问，也减少了服务器端的性能。</p>
<p goog_ds_charindex="2818" align="left">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>
<p goog_ds_charindex="2825" align="left">&nbsp;&nbsp;&nbsp;&nbsp;<strong goog_ds_charindex="2830">使用REST架构</strong></p>
<p goog_ds_charindex="2841" align="left">&nbsp;&nbsp;&nbsp;&nbsp;对于开发人员来说，关心的是如何使用REST架构，这里我们来简单谈谈这个问题。REST不仅仅是一种崭新的架构，它带来的更是一种全新的Web开发过程中的思维方式：通过URL来设计系统结构。在REST中，所有的URL都对应着资源，只要URL的设计是良好的，那么其呈现的系统结构也就是良好的。这点和TDD(Test Driven Development)很相似，他是通过测试用例来设计系统的接口，每一个测试用例都表示一系列用户的需求。开发人员不需要一开始就编写功能，而只需要把需要实现的功能通过测试用例的形式表现出来即可。这个和REST中通过URL设计系统结构的方式类似，我们只需要根据需求设计出合理地URL，这些URL不一定非要链接到指定的页面或者完成一些行为，只要它们能够直观的表现出系统的用户接口。根据这些URL，我们就可以方便的设计系统结构。从REST架构的概念上来看，所有能够被抽象成资源的东西都可以被指定为一个URL，而开发人员所需要做的工作就是如何能把用户需求抽象为资源，以及如何抽象的精确。因为对资源抽象的越为精确，对REST的应用来说就越好。这个和传统MVC开发模式中基于Action的思想差别就非常大。设计良好的URL，不但对于开发人员来说可以更明确的认识系统结构，对使用者来说也方便记忆和识别资源，因为URL足够简单和有意义。按照以往的设计模式，很多URL后面都是一堆参数，对于使用者来说也是很不方便的。</p>
<p goog_ds_charindex="3456" align="left">&nbsp;&nbsp;&nbsp;&nbsp;既然REST这么好用，那么是不是所有的Web应用都能采取此种架构呢？答案是否定的。我们知道，直到现在为止，MVC(Model-View-Controller)模式依然是Web开发最普遍的模式，绝大多数的公司和开发人员都采取此种架构来开发Web应用，并且其思维方式也停留于此。MVC模式由数据，视图和控制器构成，通过事件(Event)触发Controller来改变Model和View。加上Webwork,Struts等开源框架的加入，MVC开发模式已经相当成熟，其思想根本就是基于Action来驱动。从开发人员角度上来说，贸然接受一个新的架构会带来风险，其中的不确定因素太多。并且REST新的思维方式是把所有用户需求抽象为资源，这在实际开发中是比较难做到的，因为并不是所有的用户需求都能被抽象为资源，这样也就是说不是整个系统的结构都能通过REST的来表现。所以在开发中，我们需要根据以上2点来在REST和MVC中做出选择。我们认为比较好的办法是混用REST和MVC，因为这适合绝大多数的Web应用开发，开发人员只需要对比较容易能够抽象为资源的用户需求采取REST的开发模式，而对其它需求采取MVC开发即可。这里需要提到的就是ROR(Ruby on Rails)框架，这是一个基于Ruby语言的越来越流行的Web开发框架，它极大的提高了Web开发的速度。更为重要的是，ROR(从1.2版本起)框架是第一个引入REST做为核心思想的Web开发框架，它提供了对REST最好的支持，也是当今最成功的应用REST的Web开发框架。实际上，ROR的REST实现就是REST和MVC混用，开发人员采用ROR框架，可以更快更好的构建Web应用。</p>
<p goog_ds_charindex="4176" align="left">&nbsp;</p>
<p goog_ds_charindex="4177" align="left">&nbsp;&nbsp;&nbsp; 对开发人员来说，REST不仅仅在Web开发上贡献了自己的力量，同时也让我们学到了如何把软件工程原则系统地应用于对一个真实软件的设计和评估上。</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/119963#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Tue, 04 Sep 2007 01:07:00 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/119963</link>
        <guid>http://brainstorm.javaeye.com/blog/119963</guid>
      </item>
      <item>
        <title>Spring AOP 学习笔记 - 几种Advice的建立</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/115926" style="color:red;">http://brainstorm.javaeye.com/blog/115926</a>&nbsp;
          发表时间: 2007年08月24日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p><strong><font size="5">Creating advice:</font></strong></p>
<p>&nbsp;&nbsp;&nbsp; advice object包含了所有需要添加到aspect的逻辑代码，因为Spring中的joinpoint model是基于method interception的，所以在spring中advice object是可以加载在method调用的范围内的。Spring支持以下集中比较基本的advice类型。</p>
<p><font face="Arial"></font></p>
<p>
<table cellspacing="1" border="1" summary="" width="600" cellpadding="1">
    <caption><strong>Advice types in spring</strong></caption>
    <tbody>
        <tr>
            <td><strong>Advice type</strong></td>
            <td><strong>Interface</strong></td>
            <td><strong>Descritpion</strong></td>
        </tr>
        <tr>
            <td>Around</td>
            <td><font face="Arial">org.aopalliance.intercept.MethodInterceptor</font></td>
            <td><font face="Arial">Intercepts calls to the target<br />
            method</font></td>
        </tr>
        <tr>
            <td>Before</td>
            <td>
            <p><font face="Arial">org.springframework.aop.BeforeAdvice</font></p>
            <p><font face="Courier New">org.springframework.aop.MethodBeforeAdvice</font></p>
            <p>&nbsp;</p>
            </td>
            <td><font face="Arial">Called before the target<br />
            method is invoked</font></td>
        </tr>
        <tr>
            <td>After</td>
            <td><font face="Arial">org.springframework.aop.AfterReturningAdvice</font></td>
            <td><font face="Arial">Called after the target<br />
            method returns</font></td>
        </tr>
        <tr>
            <td><font face="Arial">Throws</font></td>
            <td><font face="Arial">org.springframework.aop.ThrowsAdvice</font></td>
            <td><font face="Arial">Called when target<br />
            method throws an<br />
            exception</font></td>
        </tr>
    </tbody>
</table>
</p>
<p>&nbsp;&nbsp;&nbsp; 以上的不同的advice类型保证了开发人员有机会在方法执行的前后和过程，甚至产生异常抛出的时候执行advice中的逻辑代码。下面是一个摘抄至Spring In action相关章节的例子。</p>
<p>&nbsp;&nbsp;&nbsp; 首先建立一个接口KwikEMart，Customer可以通过其中的buySquishee方法来购买Squishee。</p>
<div class="code_title">java 代码</div>
<p>&nbsp;</p>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">interface</span><span>&nbsp;KwikEMart&nbsp;{ &nbsp;&nbsp;</span></span> </li>
    <li class=""><span>Squishee&nbsp;buySquishee(Customer&nbsp;customer)&nbsp;</span><span class="keyword">throws</span><span>&nbsp;KwikEMartException; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;</p>
<p>&nbsp;&nbsp;&nbsp; 同时我们完成一个类ApuEwikEMart来实现它。</p>
<div class="code_title">java 代码</div>
<p>&nbsp;</p>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">class</span><span>&nbsp;ApuKwikEMart&nbsp;</span><span class="keyword">implements</span><span>&nbsp;KwikEMart&nbsp;{ &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">private</span><span>&nbsp;</span><span class="keyword">boolean</span><span>&nbsp;squisheeMachineEmpty; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">public</span><span>&nbsp;Squishee&nbsp;buySquishee(Customer&nbsp;customer) &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">throws</span><span>&nbsp;KwikEMartException&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">if</span><span>&nbsp;(customer.isBroke())&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">throw</span><span>&nbsp;</span><span class="keyword">new</span><span>&nbsp;CustomerIsBrokeException(); &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>} &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">if</span><span>&nbsp;(squisheeMachineEmpty)&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">throw</span><span>&nbsp;</span><span class="keyword">new</span><span>&nbsp;NoMoreSquisheesException(); &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">return</span><span>&nbsp;</span><span class="keyword">new</span><span>&nbsp;Squishee(); &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;</p>
<p>&nbsp;&nbsp;&nbsp; 这里定义了一些相关的异常。</p>
<p>&nbsp;&nbsp;&nbsp; 首先我们为buySquishee方法加上一个before advice。当Customer购买Squishee时，我们可以给他们一个温暖的问候。扩展<font face="Arial">org.springframework.aop.MethodBeforeAdvice接口。</font></p>
<div class="code_title">java 代码</div>
<p>&nbsp;</p>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">interface</span><span>&nbsp;MethodBeforeAdvice&nbsp;{ &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">void</span><span>&nbsp;before(Method&nbsp;method,&nbsp;Object[]&nbsp;args,&nbsp;Object&nbsp;target) &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">throws</span><span>&nbsp;Throwable &nbsp;&nbsp;</span> </li>
    <li class=""><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;</p>
<p>&nbsp;&nbsp;&nbsp; 编写一个欢迎的advice object: WelcomeAdvice来实现MethodBeforeAdvice接口。</p>
<div class="code_title">java 代码</div>
<p>&nbsp;</p>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">import</span><span>&nbsp;java.lang.reflect.Method; &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">import</span><span>&nbsp;org.springframework.aop.MethodBeforeAdvice; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">class</span><span>&nbsp;WelcomeAdvice&nbsp;</span><span class="keyword">implements</span><span>&nbsp;MethodBeforeAdvice&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">void</span><span>&nbsp;before(Method&nbsp;method,&nbsp;Object[]&nbsp;args,&nbsp;Object&nbsp;target)&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>Customer&nbsp;customer&nbsp;=&nbsp;(Customer)&nbsp;args[</span><span class="number">0</span><span>]; &nbsp;&nbsp;</span> </li>
    <li class=""><span>System.out.println(</span><span class="string">&quot;Hello&nbsp;&quot;</span><span>&nbsp;+&nbsp;customer.getName()&nbsp;+ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="string">&quot;.&nbsp;How&nbsp;are&nbsp;you&nbsp;doing?&quot;</span><span>); &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;</p>
<p>&nbsp;&nbsp;&nbsp; method参数表示当前被植入advice的方法，args包含了该方法所有的参数。下面就是把WelcomeAdvice和ApuKwikEMart连接起来。</p>
<div class="code_title">xml 代码</div>
<p>&nbsp;</p>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-xml">
    <li class="alt"><span><span class="tag">&lt;</span><span class="tag-name">beans</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="tag">&lt;</span><span class="tag-name">bean</span><span>&nbsp;</span><span class="attribute">id</span><span>=</span><span class="attribute-value">&quot;kwikEMartTarget&quot;</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="attribute">class</span><span>=</span><span class="attribute-value">&quot;com.springinaction.chapter03.store.ApuKwikEMart&quot;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="tag">&lt;</span><span class="tag-name">bean</span><span>&nbsp;</span><span class="attribute">id</span><span>=</span><span class="attribute-value">&quot;welcomeAdvice&quot;</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="attribute">class</span><span>=</span><span class="attribute-value">&quot;com.springinaction.chapter03.store.WelcomeAdvice&quot;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="tag">&lt;</span><span class="tag-name">bean</span><span>&nbsp;</span><span class="attribute">id</span><span>=</span><span class="attribute-value">&quot;kwikEMart&quot;</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="attribute">class</span><span>=</span><span class="attribute-value">&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="tag">&lt;</span><span class="tag-name">property</span><span>&nbsp;</span><span class="attribute">name</span><span>=</span><span class="attribute-value">&quot;proxyInterfaces&quot;</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="tag">&lt;</span><span class="tag-name">value</span><span class="tag">&gt;</span><span>com.springinaction.chapter03.store.KwikEMart</span><span class="tag"><span class="tag-name">value</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class=""><span></span><span class="tag"><span class="tag-name">property</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class="alt"><span></span><span class="tag">&lt;</span><span class="tag-name">property</span><span>&nbsp;</span><span class="attribute">name</span><span>=</span><span class="attribute-value">&quot;interceptorNames&quot;</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="tag">&lt;</span><span class="tag-name">list</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="tag">&lt;</span><span class="tag-name">value</span><span class="tag">&gt;</span><span>welcomeAdvice</span><span class="tag"><span class="tag-name">value</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class=""><span></span><span class="tag"><span class="tag-name">list</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class="alt"><span></span><span class="tag"><span class="tag-name">property</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class=""><span></span><span class="tag">&lt;</span><span class="tag-name">property</span><span>&nbsp;</span><span class="attribute">name</span><span>=</span><span class="attribute-value">&quot;target&quot;</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="tag">&lt;</span><span class="tag-name">ref</span><span>&nbsp;</span><span class="attribute">bean</span><span>=</span><span class="attribute-value">&quot;kwikEMartTarget&quot;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="tag"><span class="tag-name">property</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class="alt"><span></span><span class="tag"><span class="tag-name">bean</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
    <li class=""><span></span><span class="tag"><span class="tag-name">beans</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span> </span></li>
</ol>
</div>
<p>&nbsp;</p>
<p>&nbsp;&nbsp;&nbsp; <font face="Arial">org.springframework.aop.framework.ProxyFactoryBean是spring框架中很重要的一个类，它可以在不改变被代理类的前提下对其增加一些行为。这里对ApuKwikEMart做了代理，将一系列的interceptors加载在被代理类上，这里就是把welcomeAdvice加载到kwikEMartTarget上。</font></p>
<p>&nbsp;&nbsp;&nbsp; 当用户购买了squishee后，我们需要对用户表示感谢，这里就需要一个after advice来实现它。首先也是扩展<font face="Arial"><font face="Arial">org.springframework.aop.AfterReturningAdvice</font>接口。</font></p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">interface</span><span>&nbsp;AfterReturningAdvice&nbsp;{ &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">void</span><span>&nbsp;afterReturning(Object&nbsp;returnValue,&nbsp;Method&nbsp;method, &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>Object[]&nbsp;args,&nbsp;Object&nbsp;target)&nbsp;</span><span class="keyword">throws</span><span>&nbsp;Throwable &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;&nbsp;&nbsp; 然后编写ThankYouAdvice来实现它。</p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">import</span><span>&nbsp;java.lang.reflect.Method; &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">import</span><span>&nbsp;org.springframework.aop.AfterReturningAdvice; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">class</span><span>&nbsp;ThankYouAdvice&nbsp;</span><span class="keyword">implements</span><span>&nbsp;AfterReturningAdvice&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">void</span><span>&nbsp;afterReturning(Object&nbsp;returnValue,&nbsp;Method&nbsp;method, &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>Object[]&nbsp;arg2,&nbsp;Object&nbsp;target)&nbsp;</span><span class="keyword">throws</span><span>&nbsp;Throwable&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class=""><span>System.out.println(</span><span class="string">&quot;Thank&nbsp;you.&nbsp;Come&nbsp;again!&quot;</span><span>); &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>} &nbsp;&nbsp;</span> </li>
    <li class=""><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;&nbsp;&nbsp; 然后就是把ThankYouAdvice和ApuKwikEMart连接起来。其xml文件这里就不重复了。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;下面就到了Around Advice的一些简单使用说明，首先扩展<font face="Arial"><font face="Arial">org.aopalliance.intercept.MethodInterceptor接口。</font></font></p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">interface</span><span>&nbsp;MethodInterceptor&nbsp;</span><span class="keyword">extends</span><span>&nbsp;Interceptor&nbsp;{ &nbsp;&nbsp;</span></span> </li>
    <li class=""><span>Object&nbsp;invoke(MethodInvocation&nbsp;invocation)&nbsp;</span><span class="keyword">throws</span><span>&nbsp;Throwable; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;&nbsp;&nbsp; 编写<font face="Arial">OnePerCustomerInterceptor来实现此接口。</font></p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">import</span><span>&nbsp;java.util.HashSet; &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">import</span><span>&nbsp;java.util.Set; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">import</span><span>&nbsp;org.aopalliance.intercept.MethodInterceptor; &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">import</span><span>&nbsp;org.aopalliance.intercept.MethodInvocation; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">class</span><span>&nbsp;OnePerCustomerInterceptor&nbsp;</span><span class="keyword">implements</span><span>&nbsp;MethodInterceptor&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">private</span><span>&nbsp;Set&nbsp;customers&nbsp;=&nbsp;</span><span class="keyword">new</span><span>&nbsp;HashSet(); &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">public</span><span>&nbsp;Object&nbsp;invoke(MethodInvocation&nbsp;invocation) &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">throws</span><span>&nbsp;Throwable&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>Customer&nbsp;customer&nbsp;=&nbsp;(Customer)&nbsp;invocation.getArguments()[</span><span class="number">0</span><span>]; &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">if</span><span>&nbsp;(customers.contains(customer))&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">throw</span><span>&nbsp;</span><span class="keyword">new</span><span>&nbsp;KwikEMartException(</span><span class="string">&quot;One&nbsp;per&nbsp;customer.&quot;</span><span>); &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>Object&nbsp;squishee&nbsp;=&nbsp;invocation.proceed(); &nbsp;&nbsp;</span> </li>
    <li class=""><span>customers.add(customer); &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">return</span><span>&nbsp;squishee; &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;&nbsp;&nbsp; 这里需要注意的是invocation.proceed。执行invocation.proceed时就是对监视方法的执行，在此行前能访问到的信息都是方法执行前的，此后的就是方法执行后的。invocation.proceed方法返回的对象就是被监视方法的返回对象。</p>
<p>&nbsp;&nbsp;&nbsp; 当buySquishee方法执行产生异常时，我们同样可以使用Throws Advice来对其进行捕捉。查看<font face="Arial">org.springframework.aop.ThrowsAdvice接口。</font></p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">void</span><span>&nbsp;afterThrowing(Throwable&nbsp;throwable) &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">void</span><span>&nbsp;afterThrowing(Method&nbsp;method,&nbsp;Object[]&nbsp;args,&nbsp;Object&nbsp;target, &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>Throwable&nbsp;throwable)&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;&nbsp;&nbsp; 编写<font face="Arial">KwikEMartExceptionAdvice来实现以上其中一个方法。</font></p>
<div class="code_title">java 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-j">
    <li class="alt"><span><span class="keyword">import</span><span>&nbsp;org.springframework.aop.ThrowsAdvice; &nbsp;&nbsp;</span></span> </li>
    <li class=""><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">class</span><span>&nbsp;KwikEMartExceptionAdvice&nbsp;</span><span class="keyword">implements</span><span>&nbsp;ThrowsAdvice&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">void</span><span>&nbsp;afterThrowing(NoMoreSquisheesException&nbsp;e)&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class=""><span>orderMoreSquishees(); &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>} &nbsp;&nbsp;</span> </li>
    <li class=""><span></span><span class="keyword">public</span><span>&nbsp;</span><span class="keyword">void</span><span>&nbsp;afterThrowing(CustomerIsBrokeException&nbsp;e)&nbsp;{ &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>showCustomerAtmMachine(); &nbsp;&nbsp;</span> </li>
    <li class=""><span>} &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>}&nbsp;&nbsp;</span> </li>
</ol>
</div>
<p>&nbsp;&nbsp;&nbsp; 这样当buySquishee方法抛出异常时，我们就可以根据异常类型的不同执行相应的方法。</p>
          <br/>
          <span style="color:red;">
            <a href="http://brainstorm.javaeye.com/blog/115926#comments" style="color:red;">本文的讨论也很精彩，浏览讨论>></a>
          </span>
          <br/><br/><br/>
          <span style="color:#E28822;">JavaEye推荐</span>
          <br/>
          <ul class='adverts'><li><a href='/adverts/41' target='_blank'><span style="color:red;font-weight:bold;">北京: 千橡集团暨校内网诚聘软件研发工程师</span></a></li><li><a href='/adverts/42' target='_blank'><span style="color:red;font-weight:bold;">搜狐网站诚聘Java、PHP和C++工程师</span></a></li></ul>
          <br/><br/><br/>
          ]]>
        </description>
        <pubDate>Fri, 24 Aug 2007 00:48:00 +0800</pubDate>
        <link>http://brainstorm.javaeye.com/blog/115926</link>
        <guid>http://brainstorm.javaeye.com/blog/115926</guid>
      </item>
      <item>
        <title>Rails实现随机验证码</title>
        <author>cjyzpcl</author>
        <description>
          <![CDATA[
          <br/>
          作者: <a href="http://brainstorm.javaeye.com">cjyzpcl</a>&nbsp;
          链接：<a href="http://brainstorm.javaeye.com/blog/106778" style="color:red;">http://brainstorm.javaeye.com/blog/106778</a>&nbsp;
          发表时间: 2007年07月30日
          <br/><br/>
          声明：本文系JavaEye网站发布的原创博客文章，未经作者书面许可，严禁任何网站转载本文，否则必将追究法律责任！
          <br/><br/>
          <p>&nbsp;&nbsp;&nbsp; 早已经实现了，现在写下来，便于以后使用。</p>
<p>&nbsp;&nbsp;&nbsp; ValidatorImageGeneratorController.rb代码如下</p>
<div class="code_title">ruby 代码</div>
<div class="dp-highlighter">
<div class="bar"></div>
<ol class="dp-rb">
    <li class="alt"><span><span class="keyword">class</span><span>&nbsp;ValidatorImageGeneratorController&nbsp;&lt;&nbsp;ApplicationController &nbsp;&nbsp;</span></span> </li>
    <li class=""><span>&nbsp;&nbsp; &nbsp;&nbsp;</span> </li>
    <li class="alt"><span>&nbsp;&nbsp;before_filter&nbsp;</span><span class="symbol">:record_code</span><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span>&nbsp;&nbsp;skip_filter&nbsp;</span><span class="symbol">:record_url</span><span>&nbsp;&nbsp;</span> </li>
    <li class="alt"><span>&nbsp;&nbsp;</span> </li>
    <li class=""><span>&nbsp;&nbsp;</span><span class="keyword">def</span><span>&n