<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Rough Book &#187; reflection</title>
	<atom:link href="http://vivin.net/tag/reflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://vivin.net</link>
	<description>random musings of just another computer nerd</description>
	<lastBuildDate>Tue, 17 Jan 2012 23:32:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>JSTL, instanceof, and hasProperty</title>
		<link>http://vivin.net/2009/12/04/jstl-instanceof-and-hasproperty/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://vivin.net/2009/12/04/jstl-instanceof-and-hasproperty/#comments</comments>
		<pubDate>Sat, 05 Dec 2009 04:12:30 +0000</pubDate>
		<dc:creator>vivin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming and Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[custom tags]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[instanceof]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jsp]]></category>
		<category><![CDATA[jstl]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[taglibs]]></category>
		<category><![CDATA[web development]]></category>

		<guid isPermaLink="false">http://vivin.net/?p=1233</guid>
		<description><![CDATA[I&#8217;ve been doing a little bit of JSTL over the past week, especially custom tags. I&#8217;ve written custom tags in Grails before, and there you use actual Groovy code. I guess this was how custom tags used to be written (in Java), but now you can can build your own custom tags using the standard [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a little bit of <a href="http://java.sun.com/products/jsp/jstl/">JSTL</a> over the past week, especially custom tags. I&#8217;ve written custom tags in Grails before, and there you use actual Groovy code. I guess this was how custom tags used to be written (in Java), but now you can can build your own custom tags using the standard tag library. The standard tag library is still pretty useful when it comes to building custom tags. Since it&#8217;s not straight Java, it forces you think really hard about your logic. You don&#8217;t want to put any business or application logic in your tag, and you want to restrict everything to view or presentation logic. A side effect of it not being Java is that if you want to do anything extremely complicated, you&#8217;re probably better off writing the tag in Java (making sure that you don&#8217;t let any business logic creep in).</p>
<p>While writing my own custom tag, I noticed that although <em>instanceof</em> is a reserved word in the JSTL EL (expression language), it is not supported as an operator. The reason I wanted to use the <em>instanceof</em> operator is that I have an attribute that could either be a <em>List</em> or a <em>Map</em> and depending on the type, I wanted to do different things.</p>
<p>Another thing I was trying to do, was to inspect the incoming object to see if it had a certain property (reflection). JSTL uses reflection so that you can access the properties of an object via dot notation, if they follow the JavaBean naming-convention. However, there was no way for me to see if an object had a certain property. To solve both these problems, I wrote my own JSTL functions.<br />
<span id="more-1233"></span><br />
The first function I wrote was one that performed the <em>instanceof</em> operation. I created a class called <em>TagUtils</em> that contained static methods that returned primitive types (like boolean, String, or Integer). <em>instanceof</em> presents a special challenge because you can&#8217;t have the second parameter be dynamic. For example, assuming that you have an object named <em>acura</em> that&#8217;s an instance of the class <em>Car</em> and a String named <em>className</em> that holds the value &#8220;<em>Car</em>&#8220;, you can&#8217;t do <em><strong>acura</strong> instanceof <strong>className</strong></em>. You have to use reflection and create a <em>Class</em> object using the <em>forName</em> static method and then check to see if <em>acura</em> is an instance by using the <em>isInstance</em> method.</p>
<p>The second function I wrote is the <em>hasProperty</em> function which uses reflection to check whether the supplied object has a particular property. To be precise, I don&#8217;t explicitly check for the existence of the object directly. Rather, I check and see if there is a getter for that property. For example, if the property is called <em>firstName</em>, then there should be a getter called <em>getFirstName()</em>.</p>
<p>The code for the functions looks like this:</p>
<pre class="brush: java">
package util.tag;

public class TagUtils {

    //Checks to see if Object &#039;o&#039; is an instance of the class in the string &quot;className&quot;
    public static boolean instanceOf(Object o, String className) {
        boolean returnValue;

        try {
            returnValue = Class.forName(className).isInstance(o);
        }

        catch(ClassNotFoundException e) {
            returnValue = false;
        }

        return returnValue;
    }

    //Checks to see if Object &#039;o&#039; has a property specified in &quot;propertyName&quot;
    public static boolean hasProperty(Object o, String propertyName) {
        boolean methodFound = false;
        int i = 0;

        Class myClass = o.getClass();
        String methodName = &quot;get&quot; + propertyName.toUpperCase().charAt(0) + propertyName.substring(1);
        Method[] methods = myClass.getMethods();

        while(i &lt; methods.length &amp;&amp; !methodFound) {
            methodFound = methods[i].getName().compareTo(methodName) == 0;
            i++;
        }

        return methodFound;
    }
}
</pre>
<p><del datetime="2009-12-12T21:35:27+00:00">For the <em>hasProperty</em> function, you can see that I used the <em>getMethod</em> method. The second argument is an array of parameter types. Since the getter accepts no parameters, we pass in an empty array (of type <em>Class</em>).</del></p>
<p>Using exceptions in business logic is really bad, because it slows down the JVM. So the rendering will also become really slow if there are a lot of exceptions being thrown. To fix this problem, I used the <em>getMethods</em> method, which returns an array of <em>Method</em> objects. I then search the array to see if the getter I want, exists.</p>
<p>After you create your functions, you have to put them in a <em>tld</em> file. I created a one called <em>tagutils.tld</em> that I put in <em>WEB-INF</em>:</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;taglib xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd&quot;
    version=&quot;2.1&quot;&gt;
    &lt;tlib-version&gt;1.0&lt;/tlib-version&gt;
    &lt;short-name&gt;function&lt;/short-name&gt;
    &lt;uri&gt;http://tagutils&lt;/uri&gt;
    &lt;function&gt;
        &lt;name&gt;instanceOf&lt;/name&gt;
        &lt;function-class&gt;util.tag.TagUtils&lt;/function-class&gt;
        &lt;function-signature&gt;boolean instanceOf(java.lang.Object, java.lang.String)&lt;/function-signature&gt;
    &lt;/function&gt;
    &lt;function&gt;
        &lt;name&gt;hasProperty&lt;/name&gt;
        &lt;function-class&gt;util.tag.TagUtils&lt;/function-class&gt;
        &lt;function-signature&gt;boolean hasProperty(java.lang.Object, java.lang.String)&lt;/function-signature&gt;
    &lt;/function&gt;
&lt;/taglib&gt;
</pre>
<p>Once you create that file, you can use your new functions in your JSP files. To test the <em>hasProperty</em> function, I created a simple class called <em>Person</em>:</p>
<pre class="brush: java">
package domain;

public class Person {
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String toString() {
        return firstName + &quot; &quot; + lastName;
    }
}
</pre>
<p>Now I put it all together:</p>
<pre class="brush: xhtml">
&lt;%@ taglib prefix=&quot;function&quot; uri=&quot;http://tagutils&quot;%&gt;
&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jsp/jstl/core&quot; %&gt;

&lt;%@ page import=&quot;java.util.Map&quot; %&gt;
&lt;%@ page import=&quot;java.util.LinkedHashMap&quot; %&gt;
&lt;%@ page import=&quot;java.util.List&quot; %&gt;
&lt;%@ page import=&quot;java.util.ArrayList&quot; %&gt;
&lt;%@ page import=&quot;domain.Person&quot; %&gt;
&lt;%
    Map&lt;String, String&gt; myMap = new LinkedHashMap&lt;String, String&gt;();
    pageContext.setAttribute(&quot;myMap&quot;, myMap);

    List&lt;Person&gt; myList = new ArrayList&lt;Person&gt;();
    pageContext.setAttribute(&quot;myList&quot;, myList);

    pageContext.setAttribute(&quot;person&quot;, new Person(&quot;Holly&quot;, &quot;Hoo&quot;));
%&gt;

myMap is an instance of Map:
&lt;b&gt;
 &lt;c:choose&gt;
   &lt;c:when test=&quot;${function:instanceOf(myMap, &#039;java.util.Map&#039;)}&quot;&gt;true&lt;/c:when&gt;
   &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
  &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;
myList is an instance of List:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:instanceOf(myList, &#039;java.util.List&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;

myMap is an instance of List:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:instanceOf(myMap, &#039;java.util.List&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;&lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;
myList is an instance of Map:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:instanceOf(myList, &#039;java.util.Map&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;&lt;br/&gt;

Person has a property called firstName:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:hasProperty(person, &#039;firstName&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br/&gt;
Person has a property called lastName:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:hasProperty(person, &#039;lastName&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br /&gt;
Person has a property called id:
&lt;b&gt;
 &lt;c:choose&gt;
  &lt;c:when test=&quot;${function:hasProperty(person, &#039;id&#039;)}&quot;&gt;true&lt;/c:when&gt;
  &lt;c:otherwise&gt;false&lt;/c:otherwise&gt;
 &lt;/c:choose&gt;
&lt;/b&gt;&lt;br /&gt;
</pre>
<p><em><strong>Note</strong>: I have used a scriptlet in the above example simple to demonstrate the usage of the functions. The use of scriptlets in JSP is bad practice since it probably means that you are putting your business logic in your JSP. The proper place for such code is in a Controller or a Service.</em></p>
<p>As you can see from the above example, the usage is pretty simple. If everything went well, the output should look something like this:</p>
<blockquote><p>
myMap is an instance of Map: <strong>true</strong><br />
myList is an instance of List: <strong>true</strong></p>
<p>myMap is an instance of List: <strong>false</strong><br />
myList is an instance of Map: <strong>false</strong></p>
<p>Person has a property called firstName: <strong>true</strong><br />
Person has a property called lastName: <strong>true</strong><br />
Person has a property called id: <strong>false</strong>
</p></blockquote>
<p><em><b>Note</b>: Using the JSP above, the <em>true</em> and <em>false</em> values will actually be on separate lines. I broke the code up in my example for readability. In my actual code, The whole logic expression is in one line.</em></p>
<p>One important thing to note is that when you use the <em>instanceOf</em> function, you have to provide the <strong>fully-qualified class-name</strong>. Otherwise, the method will return <em>false</em>.</p>
<p><strong>UPDATE</strong></p>
<p><strong>thetoolman</strong> suggested some improvements that uses <span style = "font-family: courier new; font-weight: bold">BeanInfo</span> instead of the reflection API:</p>
<pre class="brush: java">
public class TagUtils {

    public static boolean instanceOf(Object o, String className) {
        if (o == null || className == null) {
            return false;
        }

        try {
            return Class.forName(className, false, Thread.currentThread().getContextClassLoader()).isInstance(o);
        }

        catch (ClassNotFoundException e) {
            return false;
        }
    }

    public static boolean hasProperty(Object o, String propertyName) {
        if (o == null || propertyName == null) {
            return false;
        }

        BeanInfo beanInfo;
        try {
            beanInfo = java.beans.Introspector.getBeanInfo(o.getClass());
        }

        catch (IntrospectionException e) {
            return false;
        }

        for(final PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {

            if (propertyName.equals(pd.getName())) {
                return true;
            }
        }
        return false;
    }
}
</pre>
<h4>References</h4>
<ol>
<li><a href="http://stackoverflow.com/questions/1076315/jstl-check-if-property-doesnt-exist"> JSTL: check if property doesn&#8217;t exist (stackoverflow.com)</a></li>
<li><a href="http://mindprod.com/jgloss/instanceof.html">instanceof: Java Glossary (mindprod.com)</a></li>
<li><a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html">Class (Java Platform SE 6)</a></li>
</ol>
<br /><a href="http://vivin.net/?p=1233#comments" title="Comments on &quot;JSTL, instanceof, and hasProperty&quot;"><img src="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1233" alt="Comments" /></a><img src="http://vivin.net/?ak_action=api_record_view&#38;id=1233&#38;type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://vivin.net/2009/12/04/jstl-instanceof-and-hasproperty/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:thumbnail url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1233" />
		<media:content url="http://vivin.net/wp-content/plugins/feed-comments-number/image.php?1233" medium="image">
			<media:title type="html">Comments</media:title>
		</media:content>
		<media:content url="http://vivin.net/?ak_action=api_record_view&#38;id=1233&#38;type=feed" medium="image" />
	</item>
	</channel>
</rss>

