Remove reflect code from [lang] to separate project [reflect]

git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/lang/trunk@137669 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Stephen Colebourne 2003-09-20 10:18:56 +00:00
parent 47979b1a49
commit e459236715
26 changed files with 4 additions and 4981 deletions

View File

@ -7,7 +7,7 @@
<div align="center">
<h1>The Jakarta Commons <em>Lang</em> Component</h1>
$Id: STATUS.html,v 1.49 2003/09/02 02:37:21 bayard Exp $<br />
$Id: STATUS.html,v 1.50 2003/09/20 10:18:56 scolebourne Exp $<br />
<a href="#Introduction">[Introduction]</a>
<a href="#Dependencies">[Dependencies]</a>
<a href="#Release Info">[Release Info]</a>
@ -127,7 +127,7 @@ Version 2.1
<p>Want to help? Here's some "to do" items the team has identified as possibly being in scope for Lang.
Note that all are still under discussion, so please mail the list before actioning.</p>
<ul>
<li>Reflection utilities - work underway in reflect package. Move out of [lang]?</li>
<li>Rename NumberUtils stringToInt() et al to toInt().</li>
<li>DateRange/Duration class.</li>
<li>DurationFormatUtils to be completed and made public.</li>
<li>CloneUtils - utility class to enable cloning via various different mechanisms.</li>
@ -135,7 +135,7 @@ Note that all are still under discussion, so please mail the list before actioni
<li>CharUtils - Utilities to work on a char[] in the same way as a String.</li>
<li>AStringBuffer - A StringBuffer implementation with additional methods from StringUtils.</li>
<li>O(n) - Document all algorithm-implementing methods with the order. Possibly with an O(n) on the end of each parameterm or with an @order tag.</li>
<li>Money and Currency.</li>
<li>Money and Currency. Maybe separate project.</li>
<li>Code examples - Document as many static methods as possible with example usage.</li>
<li>Faster StringTokeniser - Is Java's slow?</li>
<li>Mutable Number classes - like Integer/Double but mutable.</li>

View File

@ -1,7 +1,7 @@
<project name="Lang" default="compile" basedir=".">
<!--
"Lang" component of the Jakarta Commons Subproject
$Id: build.xml,v 1.22 2003/08/23 05:27:30 bayard Exp $
$Id: build.xml,v 1.23 2003/09/20 10:18:56 scolebourne Exp $
-->
<!-- ========== Initialize Properties ===================================== -->
<property file="${user.home}/${component.name}.build.properties"/>
@ -164,13 +164,6 @@
<classpath refid="test.classpath"/>
</java>
</target>
<target name="test.reflect" depends="compile.tests">
<echo message="Running reflect package tests ..."/>
<java classname="${test.runner}" fork="yes" failonerror="${test.failonerror}">
<arg value="org.apache.commons.lang.reflect.ReflectTestSuite"/>
<classpath refid="test.classpath"/>
</java>
</target>
<target name="test.time" depends="compile.tests">
<echo message="Running time package tests ..."/>
<java classname="${test.runner}" fork="yes" failonerror="${test.failonerror}">

View File

@ -1,468 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import org.apache.commons.lang.ArrayUtils;
/**
* <p><code>ConstructorUtils</code> contains utility methods for working for
* constructors by reflection.</p>
*
* <p>The ability is provided to break the scoping restrictions coded by the
* programmer. This can allow classes to be created that shouldn't be, for
* example new instances of an enumerated type. Thus, this facility should
* be used with care.</p>
*
* @author <a href="mailto:scolebourne@apache.org">Stephen Colebourne</a>
* @version $Id: ConstructorUtils.java,v 1.3 2003/08/18 02:22:25 bayard Exp $
*/
public class ConstructorUtils {
/**
* An empty constructor array.
*/
public static final Constructor[] EMPTY_CONSTRUCTOR_ARRAY = new Constructor[0];
/**
* <p>ConstructorUtils instances should NOT be constructed in standard programming.</p>
*
* <p>Instead, the class should be used as <code>ConstructorUtils.newInstance(...)</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public ConstructorUtils() {
}
// -------------------------------------------------------------------------
/**
* <p>Gets a public <code>Constructor</code> object by matching the
* parameter types as per the Java Language Specification.</p>
*
* @param cls Class object to find constructor for, must not
* be <code>null</code>
* @param types array of Class objects representing parameter
* types, may be <code>null</code>
* @return Constructor object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Constructor getConstructor(Class cls, Class[] types) {
return getConstructor(cls, types, false);
}
/**
* <p>Gets a public <code>Constructor</code> object by matching the
* parameter types as per the Java Language Specification.</p>
*
* @param cls Class object to find constructor for, must not
* be <code>null</code>
* @param types array of Class objects representing parameter
* types, may be <code>null</code>
* @param breakScope whether to break scope restrictions using
* the <code>setAccessible</code> method. <code>False</code> will
* only match public methods.
* @return Constructor object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Constructor getConstructor(Class cls, Class[] types, boolean breakScope) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
// try exact call first for speed
try {
getConstructorExact(cls, types, breakScope);
} catch (ReflectionException ex) {
if (types == null || types.length == 0) {
throw ex;
}
if (ex.getCause() instanceof NoSuchMethodException == false) {
throw ex;
}
}
// try to find best match
try {
Constructor[] cons = cls.getDeclaredConstructors();
for (int i = 0; i < cons.length; i++) {
if (cons[i].getParameterTypes().length == types.length) {
// TODO
}
}
return null;
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting constructor", cls.getName(), types, null), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting constructor", cls.getName(), types, null), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Gets a public <code>Constructor</code> object by exactly matching the
* parameter types.</p>
*
* @param cls Class object to find constructor for, must not
* be <code>null</code>
* @param types array of Class objects representing parameter
* types, may be <code>null</code>
* @return Constructor object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Constructor getConstructorExact(Class cls, Class[] types) {
return getConstructorExact(cls, types, false);
}
/**
* <p>Gets a <code>Constructor</code> object by exactly matching the
* parameter types.</p>
*
* @param cls Class object to find constructor for, must not
* be <code>null</code>
* @param types array of Class objects representing parameter types, may
* be <code>null</code>
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. False will only match public methods.
* @return Constructor object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Constructor getConstructorExact(Class cls, Class[] types, boolean breakScope) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
try {
if (breakScope) {
Constructor con = cls.getDeclaredConstructor(types);
if (Modifier.isPublic(con.getModifiers()) == false) {
con.setAccessible(true);
}
return con;
} else {
return cls.getConstructor(types);
}
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting constructor", cls.getName(), types, null), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting constructor", cls.getName(), types, null), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Creates a new instance using a <code>Constructor</code> and parameters.</p>
*
* @param con Class object to find constructor for, must not
* be <code>null</code>
* @param param the single parameter to pass to the constructor, may
* be <code>null</code>
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the constructor is <code>null</code>
*/
public static Object newInstance(Constructor con, Object param) {
return newInstance(con, new Object[] {param}, false);
}
/**
* <p>Creates a new instance using a <code>Constructor</code> and parameters.</p>
*
* @param con Class object to find constructor for, must not
* be <code>null</code>
* @param params array of objects to pass as parameters, may
* be <code>null</code>
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the constructor is <code>null</code>
*/
public static Object newInstance(Constructor con, Object[] params) {
return newInstance(con, params, false);
}
/**
* <p>Creates a new instance using a <code>Constructor</code> and parameters.</p>
*
* @param con Class object to find constructor for, must not
* be <code>null</code>
* @param params array of objects to pass as parameters, may
* be <code>null</code>
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public methods.
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the constructor is <code>null</code>
*/
public static Object newInstance(Constructor con, Object[] params, boolean breakScope) {
if (con == null) {
throw new IllegalArgumentException("The constructor must not be null");
}
try {
if (breakScope && Modifier.isPublic(con.getModifiers()) == false) {
con.setAccessible(true);
}
return con.newInstance(params);
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "invoking constructor", con.getDeclaringClass().getName(), con.getParameterTypes(), null), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "invoking constructor", con.getDeclaringClass().getName(), con.getParameterTypes(), null), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Creates a new instance of the specified <code>Class</code> by name.</p>
*
* @param className String class name to instantiate, must not be empty
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class name is empty
*/
public static Object newInstance(String className) {
return newInstance(className, false);
}
/**
* <p>Creates a new instance of the specified <code>Class</code> by name.</p>
*
* <p>If the constructor is not public, <code>setAccessible(true)</code>
* is used to make it accessible.</p>
*
* @param className String class name to instantiate, must not be empty
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. False will only match public methods.
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class name is empty
*/
public static Object newInstance(String className, boolean breakScope) {
Class cls = ReflectionUtils.getClass(className);
return newInstance(cls, breakScope);
}
// -------------------------------------------------------------------------
/**
* <p>Creates a new instance of the specified <code>Class</code>.</p>
*
* @param cls Class object to instantiate, must not be <code>null</code>
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Object newInstance(Class cls) {
return newInstance(cls, false);
}
/**
* <p>Creates a new instance of the specified <code>Class</code>.</p>
*
* <p>If the constructor is not public, <code>setAccessible(true)</code>
* is used to make it accessible.</p>
*
* @param cls Class object to instantiate, must not be <code>null</code>
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public methods.
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Object newInstance(Class cls, boolean breakScope) {
if (breakScope) {
return newInstanceExact(cls, null, null, true);
} else {
if (cls == null) {
throw new IllegalArgumentException("The constructor must not be null");
}
try {
return cls.newInstance();
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "instantiating class", cls.getName(), null, null), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "instantiating class", cls.getName(), null, null), ex);
}
}
}
// -------------------------------------------------------------------------
/**
* <p>Creates a new instance of the specified <code>Class</code>.</p>
*
* <p>The constructor is found by matching the
* parameter types as per the Java Language Specification.</p>
*
* @param cls Class object to instantiate, must not
* be <code>null</code>
* @param types array of Class objects representing parameter types,
* may be <code>null</code>
* @param params array of objects to pass as parameters, may
* be <code>null</code>
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Object newInstance(Class cls, Class[] types, Object[] params) {
return newInstance(cls, types, params, false);
}
/**
* <p>Creates a new instance of the specified <code>Class</code>.</p>
*
* <p>The constructor is found by matching the
* parameter types as per the Java Language Specification.</p>
*
* @param cls Class object to instantiate, must not
* be <code>null</code>
* @param types array of Class objects representing parameter types,
* may be <code>null</code>
* @param params array of objects to pass as parameters, may
* be <code>null</code>
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public methods.
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the types and params lengths differ
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Object newInstance(Class cls, Class[] types, Object[] params, boolean breakScope) {
if (ArrayUtils.isSameLength(types, params) == false) {
throw new IllegalArgumentException("The types and params lengths must be the same");
}
Constructor con = getConstructor(cls, types, breakScope);
return newInstance(con, params, breakScope);
}
// -------------------------------------------------------------------------
/**
* <p>Creates a new instance of the specified <code>Class</code>.</p>
*
* <p>The constructor is found by matching the parameter types exactly.</p>
*
* @param cls Class object to instantiate, must not
* be <code>null</code>
* @param types array of Class objects representing parameter types,
* may be <code>null</code>
* @param params array of objects to pass as parameters, may
* be <code>null</code>
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Object newInstanceExact(Class cls, Class[] types, Object[] params) {
return newInstanceExact(cls, types, params, false);
}
/**
* <p>Creates a new instance of the specified <code>Class</code>.</p>
*
* <p>The constructor is found by matching the parameter types exactly.</p>
*
* @param cls Class object to instantiate, must not
* be <code>null</code>
* @param types array of Class objects representing parameter types,
* may be <code>null</code>
* @param params array of objects to pass as parameters, may
* be <code>null</code>
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only match
* public methods.
* @return the newly created object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the types and params lengths differ
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Object newInstanceExact(Class cls, Class[] types, Object[] params, boolean breakScope) {
if (ArrayUtils.isSameLength(types, params) == false) {
throw new IllegalArgumentException("The types and params lengths must be the same");
}
Constructor con = getConstructorExact(cls, types, breakScope);
return newInstance(con, params, breakScope);
}
// -------------------------------------------------------------------------
}

View File

@ -1,518 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* <p><code>FieldUtils</code> contains utility methods for working with
* fields by reflection.</p>
*
* <p>The ability is provided to break the scoping restrictions coded by the
* programmer. This can allow fields to be changed that shouldn't be. This
* facility should be used with care.</p>
*
* @author <a href="mailto:scolebourne@apache.org">Stephen Colebourne</a>
* @version $Id: FieldUtils.java,v 1.4 2003/09/07 14:32:35 psteitz Exp $
*/
public class FieldUtils {
/**
* An empty field array.
*/
public static final Field[] EMPTY_FIELD_ARRAY = new Field[0];
/**
* <p>FieldUtils instances should NOT be constructed in standard programming.</p>
*
* <p>Instead, the class should be used as <code>FieldUtils.getField(cls, name)</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public FieldUtils() {
}
// -------------------------------------------------------------------------
/**
* <p>Gets an accessible <code>Field</code> by name respecting scope.
* Superclasses/interfaces will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Field getField(Class cls, String fieldName) {
return getField(cls, fieldName, false);
}
/**
* <p>Gets an accessible <code>Field</code> by name breaking scope
* if requested. Superclasses/interfaces will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Field getField(Class cls, String fieldName, boolean breakScope) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
if (fieldName == null) {
throw new IllegalArgumentException("The field name must not be null");
}
// Sun Java 1.3 has a bugged implementation of getField hence we write the
// code ourselves
// getField() will return the Field object with the declaring class
// set correctly to the class that declares the field. Thus requesting the
// field on a subclass will return the field from the superclass.
//
// priority order for lookup:
// searchclass private/protected/package/public
// superclass protected/package/public
// private/different package blocks access to further superclasses
// implementedinterface public
try {
// check up the superclass hierarchy
Class acls = cls;
Field match = null;
while (acls != null && acls != Object.class) {
// getDeclaredField checks for non-public scopes as well
// and it returns accurate results
try {
Field field = acls.getDeclaredField(fieldName);
if (Modifier.isPublic(field.getModifiers()) == false) {
field.setAccessible(breakScope);
return field;
}
if (breakScope == false) {
// only public acceptable if not breaking scope
throw new IllegalAccessException("The field '" + fieldName +
"' was found, but it's scope prevents direct access by reflection");
}
field.setAccessible(true);
match = field;
break;
} catch (NoSuchFieldException ex) {
// ignore
}
// next superclass
acls = acls.getSuperclass();
}
// check the public interface case. This must be manually searched for
// incase there is a public supersuperclass field hidden by a private/package
// superclass field.
// check up the superclass hierarchy
Class[] ints = cls.getInterfaces();
for (int i = 0; i < ints.length; i++) {
// getField is fine here, because everything is public, and thus it works
try {
Field field = ints[i].getField(fieldName);
return field;
} catch (NoSuchFieldException ex) {
// ignore
}
}
if (match != null) {
return match;
}
throw new NoSuchFieldException("The field '" + fieldName + "' could not be found");
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field", cls.getName(), null, fieldName), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field", cls.getName(), null, fieldName), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Gets an accessible <code>Field</code> by name respecting scope.
* Only the specified class will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Field getFieldExact(Class cls, String fieldName) {
return getFieldExact(cls, fieldName, false);
}
/**
* <p>Gets an accessible <code>Field</code> by name breaking scope
* if requested. Only the specified class will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. False will only match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Field getFieldExact(Class cls, String fieldName, boolean breakScope) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
if (fieldName == null) {
throw new IllegalArgumentException("The field name must not be null");
}
try {
// only consider the specified class by using getDeclaredField()
Field field = cls.getDeclaredField(fieldName);
if (Modifier.isPublic(field.getModifiers()) == false) {
if (breakScope) {
field.setAccessible(true);
} else {
throw new IllegalAccessException("The field '" + fieldName + "' was found, but it's scope prevents direct access by reflection");
}
}
return field;
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field", cls.getName(), null, fieldName), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field", cls.getName(), null, fieldName), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Gets a static Field value from a <code>Field</code> object.</p>
*
* @param field the field to use
* @return the field value
* @throws IllegalArgumentException if the field is
* <code>null</code> or not static
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getStaticFieldValue(Field field) {
if (field == null) {
throw new IllegalArgumentException("The field must not be null");
}
if (Modifier.isStatic(field.getModifiers()) == false) {
throw new IllegalArgumentException("The field '" + field.getName() + "' is not static");
}
return getFieldValue(field, (Object) null, false);
}
/**
* <p>Gets a static Field value from a <code>Field</code> object.</p>
*
* @param field the field to use
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public methods.
* @return the field value
* @throws IllegalArgumentException if the field is <code>null</code>
* or not static
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getStaticFieldValue(Field field, boolean breakScope) {
if (field == null) {
throw new IllegalArgumentException("The field must not be null");
}
if (Modifier.isStatic(field.getModifiers()) == false) {
throw new IllegalArgumentException("The field '" + field.getName() + "' is not static");
}
return getFieldValue(field, (Object) null, breakScope);
}
/**
* <p>Gets a Field value from a <code>Field</code> object.</p>
*
* @param field the field to use
* @param object the object to call on, may be <code>null</code>
* for static fields
* @return the field value
* @throws IllegalArgumentException if the field is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getFieldValue(Field field, Object object) {
return getFieldValue(field, object, false);
}
/**
* <p>Gets a Field value from a Field object.</p>
*
* @param field the field to use
* @param object the object to call on, may be <code>null</code>
* for static fields
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public methods.
* @return the field value
* @throws IllegalArgumentException if the field is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getFieldValue(Field field, Object object, boolean breakScope) {
if (field == null) {
throw new IllegalArgumentException("The field must not be null");
}
try {
if (breakScope && Modifier.isPublic(field.getModifiers()) == false) {
field.setAccessible(true);
}
return field.get(object);
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field value", field.getDeclaringClass().getName(), null, field.getName()), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field value", field.getDeclaringClass().getName(), null, field.getName()), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Gets a static Field value by name. The field must be public.
* Superclasses will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @return the value of the field
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getStaticFieldValue(Class cls, String fieldName) {
return getStaticFieldValue(cls, fieldName, false);
}
/**
* <p>Gets a static Field value by name. Only the specified class
* will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getStaticFieldValue(Class cls, String fieldName, boolean breakScope) {
try {
Field field = getField(cls, fieldName, breakScope);
if (Modifier.isStatic(field.getModifiers()) == false) {
throw new NoSuchMethodException("The field '" + fieldName + "' is not static");
}
return getStaticFieldValue(field, breakScope);
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field value", cls.getName(), null, fieldName), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field value", cls.getName(), null, fieldName), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Gets a static Field value by name. The field must be public.
* Only the specified class will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @return the value of the field
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getStaticFieldValueExact(Class cls, String fieldName) {
return getStaticFieldValueExact(cls, fieldName, false);
}
/**
* <p>Gets a static Field value by name. Only the specified class will
* be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getStaticFieldValueExact(Class cls, String fieldName, boolean breakScope) {
try {
Field field = getFieldExact(cls, fieldName, breakScope);
if (Modifier.isStatic(field.getModifiers()) == false) {
throw new NoSuchMethodException("The field '" + fieldName + "' is not static");
}
return getStaticFieldValue(field, breakScope);
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field value", cls.getName(), null, fieldName), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting field value", cls.getName(), null, fieldName), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Gets a Field value by name. The field must be public. Superclasses
* will be considered.</p>
*
* @param object the object to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @return the value of the field
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getFieldValue(Object object, String fieldName) {
return getFieldValue(object, fieldName, false);
}
/**
* <p>Gets a Field value by name. Only the specified class will be
* considered.</p>
*
* @param object the object to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getFieldValue(Object object, String fieldName, boolean breakScope) {
Field field = getField(object.getClass(), fieldName, breakScope);
return getFieldValue(field, object, breakScope);
}
// -------------------------------------------------------------------------
/**
* <p>Gets a Field value by name. The field must be public.
* Only the class of the specified object will be considered.</p>
*
* @param object the object to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @return the value of the field
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getFieldValueExact(Object object, String fieldName) {
return getFieldValueExact(object, fieldName, false);
}
/**
* <p<>Gets a Field value by name. Only the class of the specified
* object will be considered.</p>
*
* @param object the object to reflect, must not be <code>null</code>
* @param fieldName the field name to obtain
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Object getFieldValueExact(Object object, String fieldName, boolean breakScope) {
Field field = getFieldExact(object.getClass(), fieldName, breakScope);
return getFieldValue(field, object, breakScope);
}
}

View File

@ -1,587 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import org.apache.commons.lang.ArrayUtils;
/**
* <p><code>MethodUtils</code> contains utility methods for working for
* methods by reflection.</p>
*
* <p>The ability is provided to break the scoping restrictions coded by the
* programmer. This can break an implementation if used incorrectly. This
* facility should be used with care.</p>
*
* @author <a href="mailto:scolebourne@apache.org">Stephen Colebourne</a>
* @author Based on code from <code>BeanUtils</code> by: Craig R. McClanahan
* @author Ralph Schaer
* @author Chris Audley
* @author Rey Fran<EFBFBD>ois
* @author Gregor Ra<EFBFBD>man
* @author Jan Sorensen
* @author Robert Burrell Donkin
* @author Gary Gregory
* @version $Id: MethodUtils.java,v 1.17 2003/09/13 03:11:30 psteitz Exp $
*/
public class MethodUtils {
/**
* Debug flag.
*/
public static final boolean debug = false;
/**
* An empty method array.
*/
public static final Method[] EMPTY_METHOD_ARRAY = new Method[0];
/**
* <p>MethodUtils instances should NOT be constructed in standard programming.</p>
*
* <p>Instead, the class should be used as <code>MethodUtils.getMethod(cls, name)</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public MethodUtils() {
}
// -------------------------------------------------------------------------
/**
* <p>Gets a <code>Method</code> by name. The method must be public and take
* no parameters. Superclasses will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param methodName the field name to obtain
* @return the Method object
* @throws IllegalArgumentException if the class or method name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Method getMethod(Class cls, String methodName) {
return getMethod(cls, methodName, ArrayUtils.EMPTY_CLASS_ARRAY, false);
}
/**
* <p>Gets a <code>Method</code> by name. The method must be public.
* Superclasses will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param methodName the field name to obtain
* @param paramType the class of the parameter
* @return the Method object
* @throws IllegalArgumentException if the class or method name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Method getMethod(Class cls, String methodName, Class paramType) {
Class[] paramTypes = {paramType};
return getMethod(cls, methodName, paramTypes);
}
/**
* <p>Gets a <code>Method</code> by name.</p>
*
* <p>The method must be public. Superclasses will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param methodName the field name to obtain
* @param paramTypes the classes of the parameters
* @return the Method object
* @throws IllegalArgumentException if the class or method name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Method getMethod(Class cls, String methodName, Class[] paramTypes) {
return getMethod(cls, methodName, paramTypes, false);
}
/**
* <p>Gets a <code>Method</code> by name. Superclasses will be considered.</p>
*
* @param cls the class to reflect, must not be <code>null</code>
* @param methodName the method name to obtain
* @param paramTypes the classes of the parameters
* @param breakScope whether to break scope restrictions using the
* <code>setAccessible</code> method. <code>False</code> will only
* match public fields.
* @return the Method object
* @throws IllegalArgumentException if the class or field name
* is <code>null</code>
* @throws ReflectionException if an error occurs during reflection
*/
public static Method getMethod(Class cls, String methodName, Class[] paramTypes, boolean breakScope) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
if (methodName == null) {
throw new IllegalArgumentException("The method name must not be null");
}
try {
if (breakScope) {
try {
// most common case, always do this for speed
return cls.getMethod(methodName, paramTypes); // must be public
} catch (NoSuchMethodException ex) {
// ignore
}
Class acls = cls;
while (acls != null) {
Method[] methods = acls.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(methodName) &&
ReflectionUtils.isCompatible(paramTypes, methods[i].getParameterTypes())) {
if (Modifier.isPublic(methods[i].getModifiers())) {
methods[i].setAccessible(true);
}
return methods[i];
}
}
acls = acls.getSuperclass(); // TODO interfaces
}
throw new NoSuchMethodException("The method '" + methodName + "' could not be found");
} else {
// apply workarounds
Method method = null;
try {
method = cls.getMethod(methodName, paramTypes);
} catch(NoSuchMethodException e) {
// swallow
}
if (method == null) {
// use the same as beanutils for the moment
Method[] compatibles = getCompatibleMethods(cls, methodName, paramTypes);
if (compatibles.length > 0) {
method = compatibles[0];
}
}
return getMethod(method);
}
} catch (ReflectionException ex) {
throw ex;
} catch (LinkageError ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting method", cls.getName(), null, methodName), ex);
} catch (Exception ex) {
throw new ReflectionException(ReflectionUtils.getThrowableText(
ex, "getting method", cls.getName(), null, methodName), ex);
}
}
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) that implements the specified <code>Method</code>. If
* no such method can be found, return <code>null</code>.</p>
*
* @param method The method that we wish to call
* @return Method
*/
public static Method getMethod(Method method) {
Method accessibleMethod = getAccessibleMethod(method);
if (accessibleMethod == null) {
try {
//
// XXX Default access superclass workaround
//
// When a public class has a default access superclass
// with public methods, these methods are accessible.
// Calling them from compiled code works fine.
//
// Unfortunately, using reflection to invoke these methods
// seems to (wrongly) to prevent access even when the method
// modifer is public.
//
// The following workaround solves the problem but will only
// work from sufficiently privileges code.
//
// Better workarounds would be gratefully accepted.
//
if (ReflectionUtils.isPublicScope(method)) {
method.setAccessible(true);
accessibleMethod = method;
}
} catch (SecurityException se) {
// log but continue just in case the method.invoke works anyway
log(
"Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
se);
}
}
return (accessibleMethod);
}
// -------------------------------------------------------------------------
/**
* <p>Invoke a named method whose parameter type matches the object type.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
* <p> This is a convenient wrapper for
* {@link #invokeMethod(Object object,String methodName,Object [] args)}.
* </p>
*
* @param objectToInvoke invoke method on this object, must
* not be <code>null</code>
* @param methodName get method with this name, must not
* be <code>null</code>
* @param arg use this argument, must not be <code>null</code>
* @return Object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if any parameter is
* <code>null</code>
*/
public static Object invokeMethod(
Object objectToInvoke,
String methodName,
Object arg)
throws
ReflectionException {
if (objectToInvoke == null) {
throw new IllegalArgumentException("The object to invoke must not be null");
}
if (methodName == null) {
throw new IllegalArgumentException("The method name must not be null");
}
if (arg == null) {
throw new IllegalArgumentException("The argument must not be null");
}
Object[] args = {arg};
return invokeMethod(objectToInvoke, methodName, args);
}
/**
* <p>Invoke a named method whose parameter type matches the object type.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
* <p> This is a convenient wrapper for
* {@link #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
* </p>
*
* @param objectToInvoke invoke method on this object, must not
* be <code>null</code>
* @param methodName get method with this name, must not
* be <code>null</code>
* @param args use these arguments - treat <code>null</code>
* as empty array
* @return Object
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the objectToInvoke, methodName
* or any argument is <code>null</code>
*/
public static Object invokeMethod(
Object objectToInvoke,
String methodName,
Object[] args)
throws
ReflectionException {
if (objectToInvoke == null) {
throw new IllegalArgumentException("The object to invoke must not be null");
}
if (methodName == null) {
throw new IllegalArgumentException("The method name must not be null");
}
if (args == null) {
return invokeMethod(objectToInvoke, methodName, null, null);
} else {
int arguments = args.length;
Class parameterTypes [] = new Class[arguments];
for (int i = 0; i < arguments; i++) {
if (args[i] == null) {
throw new IllegalArgumentException("The arguments must not be null. Index " + i + " was null.");
}
parameterTypes[i] = args[i].getClass();
}
return invokeMethod(objectToInvoke, methodName, args, parameterTypes);
}
}
/**
* <p>Invoke a named method whose parameter type matches the object type.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat
* <code>null</code> as empty array
* @return Object
* @throws ReflectionException if an error occurs during reflection
*/
public static Object invokeMethod(
Object object,
String methodName,
Object[] args,
Class[] parameterTypes)
throws
ReflectionException {
if (parameterTypes == null) {
parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
Method method = getMethod(
object.getClass(),
methodName,
parameterTypes);
if (method == null) {
throw new ReflectionException("No such accessible method: " +
methodName + "() on object: " + object.getClass().getName());
}
try {
return method.invoke(object, args);
} catch (IllegalAccessException ex) {
throw new ReflectionException(
ReflectionUtils.getThrowableText(
ex, "invoking method", object.getClass().getName(), parameterTypes, methodName)
, ex);
} catch (InvocationTargetException ex) {
throw new ReflectionException(
ReflectionUtils.getThrowableText(
ex, "invoking method", object.getClass().getName(), parameterTypes, methodName)
, ex);
}
}
// -------------------------------------------------------- Private Methods
private static Method getAccessibleMethod(Method method) {
// Make sure we have a method to check
if (method == null) {
return (null);
}
// If the requested method is not public we cannot call it
if (!Modifier.isPublic(method.getModifiers())) {
log("Method is not public");
return (null);
}
// If the declaring class is public, we are done
Class clazz = method.getDeclaringClass();
if (Modifier.isPublic(clazz.getModifiers())) {
log("Class is public");
return (method);
}
if (debug) {
log("Method is in non-public class " + clazz);
}
// Check the implemented interfaces and subinterfaces
method =
getAccessibleMethodFromInterfaceNest(clazz,
method.getName(),
method.getParameterTypes());
return (method);
}
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) that implements the specified method, by scanning through
* all implemented interfaces and subinterfaces. If no such method
* can be found, return <code>null</code>.</p>
*
* <p> There isn't any good reason why this method must be private.
* It is because there doesn't seem any reason why other classes should
* call this rather than the higher level methods.</p>
*
* @param clazz Parent class for the interfaces to be checked
* @param methodName Method name of the method we wish to call
* @param parameterTypes The parameter type signatures
*/
private static Method getAccessibleMethodFromInterfaceNest
(Class clazz, String methodName, Class parameterTypes[]) {
if (debug) {
log("Finding accessible method " + methodName + " from interface nest");
}
Method method = null;
// Search up the superclass chain
for (; clazz != null; clazz = clazz.getSuperclass()) {
// Check the implemented interfaces of the parent class
Class interfaces[] = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
// Is this interface public?
if (!Modifier.isPublic(interfaces[i].getModifiers())) {
continue;
}
// Does the method exist on this interface?
try {
method = interfaces[i].getDeclaredMethod(methodName,
parameterTypes);
} catch (NoSuchMethodException e) {
// empty
}
if (method != null) {
break;
}
// Recursively check our parent interfaces
method =
getAccessibleMethodFromInterfaceNest(interfaces[i],
methodName,
parameterTypes);
if (method != null) {
break;
}
}
}
// If we found a method return it
if (method != null) {
if (debug) {
log("Found method in class " + method.getDeclaringClass());
}
return (method);
}
// We did not find anything
return (null);
}
private static Method[] getCompatibleMethods(
Class clazz,
String methodName,
Class[] parameterTypes) {
// trace logging
if (debug) {
log("Matching name=" + methodName + " on " + clazz);
}
// search through all methods
Method[] methods = clazz.getMethods();
ArrayList compatibles = new ArrayList(methods.length);
for (int i = 0, size = methods.length; i < size ; i++) {
if (debug) {
log("Checking: " + methods[i]);
}
if (methods[i].getName().equals(methodName)) {
// log some trace information
if (debug) {
log("Found matching name:" + methods[i]);
}
// compare parameters
Class[] methodsParams = methods[i].getParameterTypes();
if (ReflectionUtils.isCompatible(parameterTypes, methodsParams)) {
// get accessible version of method
Method method = getMethod(methods[i]);
if (method != null) {
compatibles.add(method);
} else {
log("Couldn't find accessible method for: " + methods[i]);
}
}
}
}
return (Method[]) compatibles.toArray(new Method[compatibles.size()]);
}
private static void log(Object o) {
if (debug) {
System.err.println(o);
}
}
private static void log(Object o, Throwable t) {
if (debug) {
System.err.println(o);
System.err.println(t);
}
}
}

View File

@ -1,107 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import org.apache.commons.lang.exception.NestableRuntimeException;
/**
* <p>Exception thrown when the Reflection process fails. The original
* error is wrapped within this one.</p>
*
* @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a>
* @version $Id: ReflectionException.java,v 1.3 2003/08/18 02:22:25 bayard Exp $
*/
public class ReflectionException extends NestableRuntimeException {
/**
* <p>Constructs a new <code>ReflectionException</code> without specified
* detail message.</p>
*/
public ReflectionException() {
super();
}
/**
* <p>Constructs a new <code>ReflectionException</code> with specified
* detail message.</p>
*
* @param msg The error message.
*/
public ReflectionException(String msg) {
super(msg);
}
/**
* <p>Constructs a new <code>ReflectionException</code> with specified
* nested <code>Throwable</code>.</p>
*
* @param cause The exception or error that caused this exception
* to be thrown.
*/
public ReflectionException(Throwable cause) {
super(cause);
}
/**
* <p>Constructs a new <code>ReflectionException</code> with specified
* detail message and nested <code>Throwable</code>.</p>
*
* @param msg The error message.
* @param cause The exception or error that caused this exception
* to be thrown.
*/
public ReflectionException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -1,416 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.StringUtils;
/**
* <p><code>ReflectionUtils</code> contains utility methods for working for
* reflection.</p>
*
* @author <a href="mailto:scolebourne@apache.org">Stephen Colebourne</a>
* @version $Id: ReflectionUtils.java,v 1.11 2003/09/07 14:32:35 psteitz Exp $
*/
public class ReflectionUtils {
/**
* <p>ReflectionUtils instances should NOT be constructed in standard programming.</p>
*
* <p>Instead, the class should be used as <code>ReflectionUtils.getShortClassName(obj)</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public ReflectionUtils() {
}
// -------------------------------------------------------------------------
/**
* <p>Tests whether the specified field or method is
* <code>static</code>.</p>
*
* @param member the member to test, must not be <code>null</code>
* @return <code>true</code> if the member is static
*/
public static boolean isStatic(Member member) {
if (member == null) {
throw new IllegalArgumentException("The member must not be null");
}
return Modifier.isStatic(member.getModifiers());
}
/**
* <p>Tests whether the specified field or method is
* <code>final</code>.</p>
*
* @param member the member to test, must not be <code>null</code>
* @return <code>true</code> if the member is final
*/
public static boolean isFinal(Member member) {
if (member == null) {
throw new IllegalArgumentException("The member must not be null");
}
return Modifier.isFinal(member.getModifiers());
}
/**
* <p>Tests whether the specified field, method or constructor is
* <code>public</code>.</p>
*
* @param member the member to test, must not be <code>null</code>
* @return <code>true</code> if the member is public scoped
*/
public static boolean isPublicScope(Member member) {
if (member == null) {
throw new IllegalArgumentException("The member must not be null");
}
return Modifier.isPublic(member.getModifiers());
}
/**
* <p>Tests whether the specified field, method or constructor is
* <code>protected</code>.</p>
*
* @param member the member to test, must not be <code>null</code>
* @return <code>true</code> if the member is protected scoped
*/
public static boolean isProtectedScope(Member member) {
if (member == null) {
throw new IllegalArgumentException("The member must not be null");
}
return Modifier.isProtected(member.getModifiers());
}
/**
* <p>Tests whether the specified field, method or constructor is
* package (default) scoped.</p>
*
* @param member the member to test, must not be <code>null</code>
* @return <code>true</code> if the member is package scoped
*/
public static boolean isPackageScope(Member member) {
return !(isPublicScope(member) || isProtectedScope(member) || isPrivateScope(member));
}
/**
* <p>Tests whether the specified field, method or constructor is
* <code>private</code>.</p>
*
* @param member the member to test, must not be <code>null</code>
* @return <code>true</code> if the member is private scoped
*/
public static boolean isPrivateScope(Member member) {
if (member == null) {
throw new IllegalArgumentException("The member must not be null");
}
return Modifier.isPrivate(member.getModifiers());
}
// -------------------------------------------------------------------------
/**
* <p>Gets a class object for the specified string.</p>
*
* @param className fully qualified class name to find,
* must not be empty or <code>null</code>
* @return Class object for class
* @throws ReflectionException if an error occurs during reflection
* @throws IllegalArgumentException if the class name is empty
*/
public static Class getClass(String className) throws ReflectionException {
if (StringUtils.isEmpty(className)) {
throw new IllegalArgumentException("The class name must not be null");
}
try {
return Class.forName(className);
} catch (LinkageError ex) {
throw new ReflectionException(getThrowableText(ex, "getting class", className, null, null), ex);
} catch (Exception ex) {
throw new ReflectionException(getThrowableText(ex, "getting class", className, null, null), ex);
}
}
// -------------------------------------------------------------------------
/**
* <p>Checks if the requested Class array is compatible with the specified
* parameter array.</p>
*
* <p>Primitive classes are handled correctly .</p>
*
* <p>In other words, a <code>boolean</code> Class will be converted to
* a <code>Boolean</code> Class and so on.</p>
*
* <p>This method also handles widening for primitives as given in section 5.1.2 of the
* <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>.
*
* @param requestedTypes the class array requested
* @param paramTypes the actual class array for the method
* @return <code>true</code> if the parameters are compatible
*/
public static boolean isCompatible(Class[] requestedTypes, Class[] paramTypes) {
if (ArrayUtils.isSameLength(requestedTypes, paramTypes) == false) {
return false;
}
if (requestedTypes == null) {
requestedTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
if (paramTypes == null) {
paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
for (int i = 0; i < requestedTypes.length; i++) {
if (isCompatible(requestedTypes[i], paramTypes[i]) == false) {
return false;
}
}
return true;
}
/**
* <p>Determine whether a type can be used as a parameter in a method invocation.
* This method handles primitive conversions correctly.</p>
*
* <p>This method also handles widening for primitives as given in section 5.1.2 of the
* <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>.
*
* @param parameterType the type of parameter accepted by the method
* @param requestedType the type of parameter being requested
*
* @return <code>true</code> if the assignment is compatible.
*/
public static boolean isCompatible(Class requestedType, Class parameterType) {
// try plain assignment
if (ClassUtils.isAssignable(requestedType, parameterType)) {
return true;
}
if (parameterType.isPrimitive()) {
// also, this method does *not* do widening - you must specify exactly
// is this the right behaviour?
if (boolean.class.equals(parameterType)) {
return Boolean.class.equals(requestedType);
}
if (byte.class.equals(parameterType)) {
return Byte.class.equals(requestedType);
}
if (short.class.equals(parameterType)) {
return (Short.class.equals(requestedType)
|| Byte.class.equals(requestedType));
}
if (char.class.equals(parameterType)) {
return Character.class.equals(requestedType);
}
if (int.class.equals(parameterType)) {
return (Integer.class.equals(requestedType)
|| Character.class.equals(requestedType)
|| Short.class.equals(requestedType)
|| Byte.class.equals(requestedType));
}
if (long.class.equals(parameterType)) {
return (Long.class.equals(requestedType)
|| Integer.class.equals(requestedType)
|| Character.class.equals(requestedType)
|| Short.class.equals(requestedType)
|| Byte.class.equals(requestedType));
}
if (float.class.equals(parameterType)) {
return (Float.class.equals(requestedType)
|| Long.class.equals(requestedType)
|| Integer.class.equals(requestedType)
|| Character.class.equals(requestedType)
|| Short.class.equals(requestedType)
|| Byte.class.equals(requestedType));
}
if (double.class.equals(parameterType)) {
return (Double.class.equals(requestedType)
|| Float.class.equals(requestedType)
|| Long.class.equals(requestedType)
|| Integer.class.equals(requestedType)
|| Character.class.equals(requestedType)
|| Short.class.equals(requestedType)
|| Byte.class.equals(requestedType));
}
}
return false;
}
/**
* <p>Converts a primitive class to its matching object class.
* Non-primitive classes are unaffected.</p>
*
* <p>In other words, a <code>boolean</code> Class will be converted to
* a <code>Boolean</code> Class and so on.</p>
*
* @param cls the class to convert
* @return converted class
* @throws IllegalArgumentException if the class is <code>null</code>
*/
public static Class convertPrimitiveClass(Class cls) {
if (cls == null) {
throw new IllegalArgumentException("The class must not be null");
}
if (cls.isPrimitive()) {
if (Integer.TYPE.equals(cls)) {
return Integer.class;
} else if (Long.TYPE.equals(cls)) {
return Long.class;
} else if (Boolean.TYPE.equals(cls)) {
return Boolean.class;
} else if (Double.TYPE.equals(cls)) {
return Double.class;
} else if (Float.TYPE.equals(cls)) {
return Float.class;
} else if (Character.TYPE.equals(cls)) {
return Character.class;
} else if (Short.TYPE.equals(cls)) {
return Short.class;
} else if (Byte.TYPE.equals(cls)) {
return Byte.class;
}
}
return cls;
}
// -------------------------------------------------------------------------
/**
* <p>Produces nicely formatted informational error messages for reflection
* errors.</p>
*
* @param th the throwable
* @param desc the short description of the action, such as 'getting field'
* @param className the class name being used
* @param types the parameter types
* @param memberName the name of the field or method
* @return a suitable error message
*/
public static String getThrowableText(Throwable th, String desc, String className, Class[] types, String memberName) {
String message = null;
try {
throw th;
} catch (NoSuchMethodException ex) {
message = "the method does not exist";
} catch (NoSuchFieldException ex) {
message = "the field does not exist";
} catch (ClassNotFoundException ex) {
message = "the class could not be found in the classpath";
} catch (InvocationTargetException ex) {
message = "the method threw an exception";
} catch (InstantiationException ex) {
message = "the class is abstract/interface/array/primitive";
} catch (IllegalAccessException ex) {
message = "the method was not public/accessible";
} catch (IllegalArgumentException ex) {
message = "the parameters did not match those expected";
} catch (SecurityException ex) {
message = "the security manager prevents reflection";
} catch (ExceptionInInitializerError ex) {
message = "the class initialization for static variables threw an exception";
} catch (ClassCircularityError ex) {
message = "a circularity has been detected while initializing a class";
} catch (ClassFormatError ex) {
message = "the class file is malformed or otherwise cannot be interpreted as a class";
} catch (IncompatibleClassChangeError ex) {
message = "the method references another class that has changed incompatibly since compile time";
} catch (UnsatisfiedLinkError ex) {
message = "no implementation found for a native method";
} catch (VerifyError ex) {
message = "the class file contains an internal inconsistency or security problem";
} catch (NoClassDefFoundError ex) {
message = "the class references another class that was present at compile time but is no longer available";
} catch (LinkageError ex) {
message = "the class references another class that has changed incompatibly since compile time";
} catch (Throwable ex) {
message = null;
}
StringBuffer buf = new StringBuffer();
buf.append(ClassUtils.getShortClassName(th, ""));
buf.append(" while ");
buf.append(desc);
buf.append(" on Class '");
buf.append(className);
buf.append('\'');
if (types != null) {
buf.append(" for types ");
buf.append(ArrayUtils.toString(types));
}
if (memberName != null) {
buf.append(" for method '");
buf.append(memberName);
buf.append('\'');
}
if (message != null) {
buf.append(" - ");
buf.append(message);
}
return buf.toString();
}
}

View File

@ -1,26 +0,0 @@
<html>
<head>
</head>
<body>
<p>Assists in reflection with the aim to create a simple, clean and clear API which can be built upon on by more
sophisticated introspection schemes as well as fixes for bugs found in various
Java implementations.</p>
<h2>Accessibility Rules</h2>
<p>These determine which methods are in scope</p>
<h3>Java Language Specification Rules</h3>
<p>The <em>Java Language Specification Rules</em> are those that are given in the
<em>Java Language Specification</em> as applied by the compiler.
The aim of those methods who contract is given as the <em>Java Language Specification</em>
is to behave in an identical manner to compiled code.
In other words, any code that would compile should be found by reflection
and any code that would not should not</p>
<h4>Java 1.3 And Below</h4>
<p>This aim is actually easier said than done for some java versions.
The reflection implementation is slow and buggy.
If you are using one of these easier java versions, then you will probably find our code
more reliable than the standard java implementation.</p>
@since 3.0
</body>
</html>

View File

@ -1,74 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
public class AbstractChild implements Child {
private String name;
protected void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}

View File

@ -1,94 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
public abstract class AbstractParent {
private Child child;
public Child getChild()
{
return child;
}
/**
* Method which matches signature but which has wrong parameters
*/
public String testAddChild(String badParameter) {
return null;
}
/**
* Method which matches signature but which has wrong parameters
*/
public String testAddChild2(String ignore, String badParameter) {
return null;
}
public String testAddChild(Child child) {
this.child = child;
return child.getName();
}
public String testAddChild2(String ignore, Child child) {
this.child = child;
return child.getName();
}
}

View File

@ -1,80 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
public class AlphaBean extends AbstractParent implements Child {
private String name;
public AlphaBean(String name) {
setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Used for testing that correct exception is thrown.
*/
public void bogus(String badParameter){}
}

View File

@ -1,65 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
public class BetaBean extends AbstractChild {
public BetaBean(String name) {
setName(name);
}
}

View File

@ -1,64 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
public interface Child {
public String getName();
}

View File

@ -1,582 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.lang.reflect.priv.PrivateBeanFactory;
import org.apache.commons.lang.reflect.priv.PublicSubBean;
/**
* <p> Test case for <code>MethodUtils</code> </p>
*
*/
public class MethodUtilsTestCase extends TestCase {
// ---------------------------------------------------- Instance Variables
protected PrivateBeanFactory privateBeanFactory;
// ---------------------------------------------------------- Constructors
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public MethodUtilsTestCase(String name) {
super(name);
}
// -------------------------------------------------- Overall Test Methods
/**
* Set up instance variables required by this test case.
*/
public void setUp() {
privateBeanFactory = new PrivateBeanFactory();
}
/**
* Return the tests included in this test suite.
*/
public static Test suite() {
return (new TestSuite(MethodUtilsTestCase.class));
}
/**
* Tear down instance variables required by this test case.
*/
public void tearDown() {
privateBeanFactory = null;
}
// ------------------------------------------------ Individual Test Methods
/**
* <p> Test <code>getAccessibleMethod</code>.
*/
public void testGetAccessibleMethod() {
// test MethodUtils.getAccessibleMethod
// we'll make things easier by using the convenience methods
// easy bit first - find a public method
// METHOD ONE
Method method = MethodUtils.getMethod
(TestBean.class, "setStringProperty", String.class);
// check that we've found one that matches
assertNotNull(method);
assertEquals("method ONE is named correctly",
"setStringProperty", method.getName());
assertTrue("Method ONE is public",
Modifier.isPublic(method.getModifiers()));
// trickier this one - find a method in a direct interface
// METHOD TWO
method = MethodUtils.getMethod
(privateBeanFactory.create().getClass(),
"methodBar",
String.class);
// check that we've found one that matches
assertNotNull(method);
assertEquals("Method TWO is named correctly",
"methodBar", method.getName());
assertTrue("Method TWO is public",
Modifier.isPublic(method.getModifiers()));
// trickier this one - find a method in a indirect interface
// METHOD THREE
method = MethodUtils.getMethod
(privateBeanFactory.createSubclass().getClass(),
"methodBaz",
String.class);
// check that we've found one that matches
assertNotNull(method);
assertEquals("Method THREE is named correctly",
"methodBaz", method.getName());
assertTrue("Method THREE is public",
Modifier.isPublic(method.getModifiers()));
}
/**
* <p> Test <code>invokeMethod</code>.
*/
public void testinvokeMethod2() {
// test MethodUtils.invokeMethod
// easy bit first - invoke a public method
// METHOD ONE
try {
TestBean bean = new TestBean();
Object ret = MethodUtils.invokeMethod(bean, "setStringProperty", "TEST");
// check that the return's right and that the properties been set
assertNull(ret);
assertEquals("Method ONE was invoked", "TEST", bean.getStringProperty());
} catch (Throwable t) {
// ONE
fail("Exception in method ONE prevented invocation: " + t.toString());
}
// trickier this one - find a method in a direct interface
// METHOD TWO FAILURE
try {
Object ret = MethodUtils.invokeMethod(
privateBeanFactory.create(),
"methodBar",
"ANOTHER TEST");
// check that we've found one that matches
assertEquals("Method TWO was invoked correctly", "ANOTHER TEST", ret);
} catch (Throwable t) {
// METHOD TWO FAILURE
fail("Exception in method TWO prevented invocation: " + t.toString());
}
// trickier this one - find a method in a indirect interface
// METHOD THREE
try {
Object ret = MethodUtils.invokeMethod(
privateBeanFactory.createSubclass(),
"methodBaz",
"YET ANOTHER TEST");
// check that we've found one that matches
assertEquals("Method TWO was invoked correctly", "YET ANOTHER TEST", ret);
} catch (Throwable t) {
// METHOD THREE FAILURE
fail("Exception in method THREE prevented invocation: " + t.toString());
}
}
/**
* <p> Test <code>invokeMethod</code>.
*/
public void testInvokeMethod() throws Exception {
// i'm going to test that the actual calls work first and then try them via reflection
AbstractParent parent = new AlphaBean("parent");
// try testAddChild through abstract superclass
BetaBean childOne = new BetaBean("ChildOne");
assertEquals("Oh no! Badly coded test case! (1)", "ChildOne", parent.testAddChild(childOne));
// let's try MethodUtils version
assertEquals(
"Cannot invoke through abstract class (1)",
"ChildOne",
MethodUtils.invokeMethod(parent, "testAddChild", childOne));
// try adding through interface
AlphaBean childTwo = new AlphaBean("ChildTwo");
assertEquals("Oh no! Badly coded test case! (2)", "ChildTwo", parent.testAddChild(childTwo));
// let's try MethodUtils version
assertEquals(
"Cannot invoke through interface (1)",
"ChildTwo",
MethodUtils.invokeMethod(parent, "testAddChild", childTwo));
Object[] params = new Object[2];
assertEquals("Oh no! Badly coded test case! (3)", "ChildOne", parent.testAddChild2("parameter", childOne));
// let's try MethodUtils version
params[0] = "parameter";
params[1] = childOne;
assertEquals(
"Cannot invoke through abstract class (1)",
"ChildOne",
MethodUtils.invokeMethod(parent, "testAddChild2", params));
assertEquals("Oh no! Badly coded test case! (4)", "ChildTwo", parent.testAddChild2("parameter", childTwo));
// let's try MethodUtils version
params[0] = "parameter";
params[1] = childTwo;
assertEquals(
"Cannot invoke through abstract class (1)",
"ChildTwo",
MethodUtils.invokeMethod(parent, "testAddChild2", params));
// test that exception is correctly thrown when a method cannot be found with matching params
try {
// the next line
parent = new AlphaBean("parent");
childOne = new BetaBean("ChildOne");
MethodUtils.invokeMethod(parent, "bogus", childOne);
// should get here!
fail("No exception thrown when no appropriate method exists");
} catch (ReflectionException e) {
// this is what we're expecting!
}
MethodUtils.invokeMethod(parent, "getName", null);
MethodUtils.invokeMethod(parent, "getName", null, null);
MethodUtils.invokeMethod(parent, "getName", null);
MethodUtils.invokeMethod(parent, "getName", null, null);
}
/**
* <p> Test <code>invokeMethod</code> with a primitive.
*/
public void testInvokeMethodWithPrimitives() throws Exception {
// first test that the bean works
PrimitiveBean bean = new PrimitiveBean();
bean.setFloat(20.0f);
bean.setLong(10l);
bean.setBoolean(true);
bean.setInt(12);
bean.setDouble(25.5d);
assertEquals("Bug in PrimitiveBean (1)", 20.0f, bean.getFloat(), 0.01f);
assertEquals("Bug in PrimitiveBean (2)", 10, bean.getLong());
assertEquals("Bug in PrimitiveBean (3)", true, bean.getBoolean());
assertEquals("Bug in PrimitiveBean (4)", 12, bean.getInt());
assertEquals("Bug in PrimitiveBean (5)", 25.5d, bean.getDouble(), 0.01f);
bean = new PrimitiveBean();
MethodUtils.invokeMethod(bean, "setBoolean", new Boolean(true));
assertEquals("Call boolean property using invokeMethod", true, bean.getBoolean());
bean = new PrimitiveBean();
MethodUtils.invokeMethod(bean, "setFloat", new Float(20.0f));
assertEquals("Call float property using invokeMethod", 20.0f, bean.getFloat(), 0.01f);
bean = new PrimitiveBean();
MethodUtils.invokeMethod(bean, "setLong", new Long(10));
assertEquals("Call float property using invokeMethod", 10, bean.getLong());
bean = new PrimitiveBean();
MethodUtils.invokeMethod(bean, "setInt", new Integer(12));
assertEquals("Set float property using invokeMethod", 12, bean.getInt());
bean = new PrimitiveBean();
MethodUtils.invokeMethod(bean, "setDouble", new Double(25.5d));
assertEquals("Set float property using invokeMethod", 25.5d, bean.getDouble(), 0.01d);
}
/**
* Simple tests for accessing static methods via invokeMethod().
*/
public void testSimpleStatic1() {
TestBean bean = new TestBean();
Object value = null;
int current = TestBean.currentCounter();
try {
// Return initial value of the counter
value = MethodUtils.invokeMethod
(bean, "currentCounter", new Object[0], new Class[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
// Increment via no-arguments version
MethodUtils.invokeMethod
(bean, "incrementCounter", new Object[0], new Class[0]);
// Validate updated value
current++;
value = MethodUtils.invokeMethod
(bean, "currentCounter", new Object[0], new Class[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
// Increment via specified-argument version
MethodUtils.invokeMethod
(bean, "incrementCounter",
new Object[] { new Integer(5) },
new Class[] { Integer.TYPE });
// Validate updated value
current += 5;
value = MethodUtils.invokeMethod
(bean, "currentCounter", new Object[0], new Class[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
} catch (Exception e) {
fail("Threw exception" + e);
}
}
/**
* Simple tests for accessing static methods via invokeMethod().
*/
public void testSimpleStatic2() {
TestBean bean = new TestBean();
Object value = null;
int current = TestBean.currentCounter();
try {
// Return initial value of the counter
value = MethodUtils.invokeMethod
(bean, "currentCounter", new Object[0], new Class[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
// Increment via no-arguments version
MethodUtils.invokeMethod
(bean, "incrementCounter", new Object[0], new Class[0]);
// Validate updated value
current++;
value = MethodUtils.invokeMethod
(bean, "currentCounter", new Object[0], new Class[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
// Increment via specified-argument version
MethodUtils.invokeMethod
(bean, "incrementCounter",
new Object[] { new Integer(5) },
new Class[] { Integer.TYPE });
// Validate updated value
current += 5;
value = MethodUtils.invokeMethod
(bean, "currentCounter", new Object[0], new Class[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
} catch (Exception e) {
fail("Threw exception" + e);
}
}
/**
* Simple tests for accessing static methods via getAccessibleMethod()
*/
public void testSimpleStatic3() {
Object value = null;
int current = TestBean.currentCounter();
try {
// Acquire the methods we need
Method currentCounterMethod = MethodUtils.getMethod
(TestBean.class, "currentCounter",
new Class[0]);
assertNotNull("currentCounterMethod exists",
currentCounterMethod);
assertEquals("currentCounterMethod name",
"currentCounter",
currentCounterMethod.getName());
assertEquals("currentCounterMethod args",
0,
currentCounterMethod.getParameterTypes().length);
assertTrue("currentCounterMethod public",
Modifier.isPublic(currentCounterMethod.getModifiers()));
assertTrue("currentCounterMethod static",
Modifier.isStatic(currentCounterMethod.getModifiers()));
Method incrementCounterMethod1 = MethodUtils.getMethod
(TestBean.class, "incrementCounter",
new Class[0]);
assertNotNull("incrementCounterMethod1 exists",
incrementCounterMethod1);
assertEquals("incrementCounterMethod1 name",
"incrementCounter",
incrementCounterMethod1.getName());
assertEquals("incrementCounterMethod1 args",
0,
incrementCounterMethod1.getParameterTypes().length);
assertTrue("incrementCounterMethod1 public",
Modifier.isPublic(incrementCounterMethod1.getModifiers()));
assertTrue("incrementCounterMethod1 static",
Modifier.isStatic(incrementCounterMethod1.getModifiers()));
Method incrementCounterMethod2 = MethodUtils.getMethod
(TestBean.class, "incrementCounter",
new Class[] { Integer.TYPE });
assertNotNull("incrementCounterMethod2 exists",
incrementCounterMethod2);
assertEquals("incrementCounterMethod2 name",
"incrementCounter",
incrementCounterMethod2.getName());
assertEquals("incrementCounterMethod2 args",
1,
incrementCounterMethod2.getParameterTypes().length);
assertTrue("incrementCounterMethod2 public",
Modifier.isPublic(incrementCounterMethod2.getModifiers()));
assertTrue("incrementCounterMethod2 static",
Modifier.isStatic(incrementCounterMethod2.getModifiers()));
// Return initial value of the counter
value = currentCounterMethod.invoke(null, new Object[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
// Increment via no-arguments version
incrementCounterMethod1.invoke(null, new Object[0]);
// Validate updated value
current++;
value = currentCounterMethod.invoke(null, new Object[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
// Increment via specified-argument version
incrementCounterMethod2.invoke(null,
new Object[] { new Integer(5) });
// Validate updated value
current += 5;
value = currentCounterMethod.invoke(null, new Object[0]);
assertNotNull("currentCounter exists", value);
assertTrue("currentCounter type",
value instanceof Integer);
assertEquals("currentCounter value",
current,
((Integer) value).intValue());
} catch (Exception e) {
fail("Threw exception" + e);
}
}
public void testPublicSub() throws Exception {
// make sure that bean does what it should
PublicSubBean bean = new PublicSubBean();
assertEquals("Start value (foo)", bean.getFoo(), "This is foo");
assertEquals("Start value (bar)", bean.getBar(), "This is bar");
bean.setFoo("new foo");
bean.setBar("new bar");
assertEquals("Set value (foo)", bean.getFoo(), "new foo");
assertEquals("Set value (bar)", bean.getBar(), "new bar");
// see if we can access public methods in a default access superclass
// from a public access subclass instance
MethodUtils.invokeMethod(bean, "setFoo", "alpha");
assertEquals("Set value (foo:2)", bean.getFoo(), "alpha");
MethodUtils.invokeMethod(bean, "setBar", "beta");
assertEquals("Set value (bar:2)", bean.getFoo(), "alpha");
}
}

View File

@ -1,119 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
/**
* Bean that has primitive properties
*/
public class PrimitiveBean {
private float _float;
private double _double;
private boolean _boolean;
private long _long;
private int _int;
private short _short;
public short getShort() {
return _short;
}
public void setShort(short _short) {
this._short = _short;
}
public float getFloat() {
return _float;
}
public void setFloat(float _float) {
this._float = _float;
}
public double getDouble() {
return _double;
}
public void setDouble(double _double) {
this._double = _double;
}
public boolean getBoolean() {
return _boolean;
}
public void setBoolean(boolean _boolean) {
this._boolean = _boolean;
}
public long getLong() {
return _long;
}
public void setLong(long _long) {
this._long = _long;
}
public int getInt() {
return _int;
}
public void setInt(int _int) {
this._int = _int;
}
}

View File

@ -1,94 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Test suite for the Reflect packages.
*
* @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> (of original copied from)
* @author Robert Burrell Donkin
* @version $Id: ReflectTestSuite.java,v 1.3 2003/08/18 02:22:28 bayard Exp $
*/
public class ReflectTestSuite extends TestCase {
/**
* Construct a new instance.
*/
public ReflectTestSuite(String name) {
super(name);
}
/**
* Executor-line interface.
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* Get the suite of tests
*/
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(MethodUtilsTestCase.suite());
suite.addTest(ReflectionUtilsTestCase.suite());
return suite;
}
}

View File

@ -1,279 +0,0 @@
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.Member;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* <p> Test case for <code>ReflectionUtils</code> </p>
*
*/
public class ReflectionUtilsTestCase extends TestCase {
// ---------------------------------------------------- Instance Variables
// ---------------------------------------------------------- Constructors
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public ReflectionUtilsTestCase(String name) {
super(name);
}
// -------------------------------------------------- Overall Test Methods
/**
* Set up instance variables required by this test case.
*/
public void setUp() {
// any set up goes here
}
/**
* Return the tests included in this test suite.
*/
public static Test suite() {
return (new TestSuite(ReflectionUtilsTestCase.class));
}
/**
* Tear down instance variables required by this test case.
*/
public void tearDown() {
// any tear down goes here
}
// ------------------------------------------------ Individual Test Methods
public void testScopeUtils() throws Exception {
ScopeBean bean = new ScopeBean();
Member field = bean.getPrivateField();
assertEquals("Private scope (field) [isFinal]", false ,ReflectionUtils.isFinal(field));
assertEquals("Private scope (field) [isPackageScope]", false, ReflectionUtils.isPackageScope(field));
assertEquals("Private scope (field) [isPrivateScope]", true, ReflectionUtils.isPrivateScope(field));
assertEquals("Private scope (field) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(field));
assertEquals("Private scope (field) [isPublicScope]", false, ReflectionUtils.isPublicScope(field));
assertEquals("Private scope (field) [isStatic]", false, ReflectionUtils.isStatic(field));
Member method = bean.getPrivateMethod();
assertEquals("Private scope (method) [isFinal]", false, ReflectionUtils.isFinal(method));
assertEquals("Private scope (method) [isPackageScope]", false, ReflectionUtils.isPackageScope(method));
assertEquals("Private scope (method) [isPrivateScope]", true, ReflectionUtils.isPrivateScope(method));
assertEquals("Private scope (method) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(method));
assertEquals("Private scope (method) [isPublicScope]", false, ReflectionUtils.isPublicScope(method));
assertEquals("Private scope (method) [isStatic]", false, ReflectionUtils.isStatic(method));
field = bean.getPackageField();
assertEquals("Package scope (field) [isFinal]", false, ReflectionUtils.isFinal(field));
assertEquals("Package scope (field) [isPackageScope]", true, ReflectionUtils.isPackageScope(field));
assertEquals("Package scope (field) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(field));
assertEquals("Package scope (field) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(field));
assertEquals("Package scope (field) [isPublicScope]", false, ReflectionUtils.isPublicScope(field));
assertEquals("Package scope (field) [isStatic]", false, ReflectionUtils.isStatic(field));
method = bean.getPackageMethod();
assertEquals("Package scope (method) [isFinal]", false, ReflectionUtils.isFinal(method));
assertEquals("Package scope (method) [isPackageScope]", true, ReflectionUtils.isPackageScope(method));
assertEquals("Package scope (method) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(method));
assertEquals("Package scope (method) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(method));
assertEquals("Package scope (method) [isPublicScope]", false, ReflectionUtils.isPublicScope(method));
assertEquals("Packages scope (method) [isStatic]", false, ReflectionUtils.isStatic(method));
field = bean.getPublicField();
assertEquals("Public scope (field) [isFinal]", false, ReflectionUtils.isFinal(field));
assertEquals("Public scope (field) [isPackageScope]", false, ReflectionUtils.isPackageScope(field));
assertEquals("Public scope (field) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(field));
assertEquals("Public scope (field) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(field));
assertEquals("Public scope (field) [isPublicScope]", true, ReflectionUtils.isPublicScope(field));
assertEquals("Public scope (field) [isStatic]", false, ReflectionUtils.isStatic(field));
method = bean.getPublicMethod();
assertEquals("Public scope (method) [isFinal]", false, ReflectionUtils.isFinal(method));
assertEquals("Public scope (method) [isPackageScope]", false, ReflectionUtils.isPackageScope(method));
assertEquals("Public scope (method) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(method));
assertEquals("Public scope (method) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(method));
assertEquals("Public scope (method) [isPublicScope]", true, ReflectionUtils.isPublicScope(method));
assertEquals("Public scope (method) [isStatic]", false, ReflectionUtils.isStatic(method));
field = bean.getFinalField();
assertEquals("Final scope (field) [isFinal]", true, ReflectionUtils.isFinal(field));
assertEquals("Final scope (field) [isPackageScope]", false, ReflectionUtils.isPackageScope(field));
assertEquals("Final scope (field) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(field));
assertEquals("Final scope (field) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(field));
assertEquals("Final scope (field) [isPublicScope]", true, ReflectionUtils.isPublicScope(field));
assertEquals("Final scope (field) [isStatic]", false, ReflectionUtils.isStatic(field));
method = bean.getFinalMethod();
assertEquals("Final scope (method) [isFinal]", true, ReflectionUtils.isFinal(method));
assertEquals("Final scope (method) [isPackageScope]", false, ReflectionUtils.isPackageScope(method));
assertEquals("Final scope (method) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(method));
assertEquals("Final scope (method) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(method));
assertEquals("Final scope (method) [isPublicScope]", true, ReflectionUtils.isPublicScope(method));
assertEquals("Final scope (method) [isStatic]", false, ReflectionUtils.isStatic(method));
field = bean.getStaticField();
assertEquals("Static scope (field) [isFinal]", false, ReflectionUtils.isFinal(field));
assertEquals("Static scope (field) [isPackageScope]", false, ReflectionUtils.isPackageScope(field));
assertEquals("Static scope (field) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(field));
assertEquals("Static scope (field) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(field));
assertEquals("Static scope (field) [isPublicScope]", true, ReflectionUtils.isPublicScope(field));
assertEquals("Static scope (field) [isStatic]", true, ReflectionUtils.isStatic(field));
method = bean.getStaticMethod();
assertEquals("Static scope (method) [isFinal]", false, ReflectionUtils.isFinal(method));
assertEquals("Static scope (method) [isPackageScope]", false, ReflectionUtils.isPackageScope(method));
assertEquals("Static scope (method) [isPrivateScope]", false, ReflectionUtils.isPrivateScope(method));
assertEquals("Static scope (method) [isProtectedScope]", false, ReflectionUtils.isProtectedScope(method));
assertEquals("Static scope (method) [isPublicScope]", true, ReflectionUtils.isPublicScope(method));
assertEquals("Static scope (method) [isStatic]", true, ReflectionUtils.isStatic(method));
}
public void testWidening() throws Exception
{
// test byte conversions
assertEquals("byte -> char", ReflectionUtils.isCompatible(Byte.class, char.class), false);
assertEquals("byte -> byte", ReflectionUtils.isCompatible(Byte.class, byte.class), true);
assertEquals("byte -> short", ReflectionUtils.isCompatible(Byte.class, short.class), true);
assertEquals("byte -> int", ReflectionUtils.isCompatible(Byte.class, int.class), true);
assertEquals("byte -> long", ReflectionUtils.isCompatible(Byte.class, long.class), true);
assertEquals("byte -> float", ReflectionUtils.isCompatible(Byte.class, float.class), true);
assertEquals("byte -> double", ReflectionUtils.isCompatible(Byte.class, double.class), true);
assertEquals("byte -> boolean", ReflectionUtils.isCompatible(Byte.class, boolean.class), false);
// test short conversions
assertEquals("short -> char", ReflectionUtils.isCompatible(Short.class, char.class), false);
assertEquals("short -> byte", ReflectionUtils.isCompatible(Short.class, byte.class), false);
assertEquals("short -> short", ReflectionUtils.isCompatible(Short.class, short.class), true);
assertEquals("short -> int", ReflectionUtils.isCompatible(Short.class, int.class), true);
assertEquals("short -> long", ReflectionUtils.isCompatible(Short.class, long.class), true);
assertEquals("short -> float", ReflectionUtils.isCompatible(Short.class, float.class), true);
assertEquals("short -> double", ReflectionUtils.isCompatible(Short.class, double.class), true);
assertEquals("short -> boolean", ReflectionUtils.isCompatible(Short.class, boolean.class), false);
// test char conversions
assertEquals("char -> char", ReflectionUtils.isCompatible(Character.class, char.class), true);
assertEquals("char -> byte", ReflectionUtils.isCompatible(Character.class, byte.class), false);
assertEquals("char -> short", ReflectionUtils.isCompatible(Character.class, short.class), false);
assertEquals("char -> int", ReflectionUtils.isCompatible(Character.class, int.class), true);
assertEquals("char -> long", ReflectionUtils.isCompatible(Character.class, long.class), true);
assertEquals("char -> float", ReflectionUtils.isCompatible(Character.class, float.class), true);
assertEquals("char -> double", ReflectionUtils.isCompatible(Character.class, double.class), true);
assertEquals("char -> boolean", ReflectionUtils.isCompatible(Character.class, boolean.class), false);
// test int conversions
assertEquals("int -> char", ReflectionUtils.isCompatible(Integer.class, char.class), false);
assertEquals("int -> byte", ReflectionUtils.isCompatible(Integer.class, byte.class), false);
assertEquals("int -> short", ReflectionUtils.isCompatible(Integer.class, short.class), false);
assertEquals("int -> int", ReflectionUtils.isCompatible(Integer.class, int.class), true);
assertEquals("int -> long", ReflectionUtils.isCompatible(Integer.class, long.class), true);
assertEquals("int -> float", ReflectionUtils.isCompatible(Integer.class, float.class), true);
assertEquals("int -> double", ReflectionUtils.isCompatible(Integer.class, double.class), true);
assertEquals("int -> boolean", ReflectionUtils.isCompatible(Integer.class, boolean.class), false);
// test long conversions
assertEquals("long -> char", ReflectionUtils.isCompatible(Long.class, char.class), false);
assertEquals("long -> byte", ReflectionUtils.isCompatible(Long.class, byte.class), false);
assertEquals("long -> short", ReflectionUtils.isCompatible(Long.class, short.class), false);
assertEquals("long -> int", ReflectionUtils.isCompatible(Long.class, int.class), false);
assertEquals("long -> long", ReflectionUtils.isCompatible(Long.class, long.class), true);
assertEquals("long -> float", ReflectionUtils.isCompatible(Long.class, float.class), true);
assertEquals("long -> double", ReflectionUtils.isCompatible(Long.class, double.class), true);
assertEquals("long -> boolean", ReflectionUtils.isCompatible(Long.class, boolean.class), false);
// test float conversions
assertEquals("float -> char", ReflectionUtils.isCompatible(Float.class, char.class), false);
assertEquals("float -> byte", ReflectionUtils.isCompatible(Float.class, byte.class), false);
assertEquals("float -> short", ReflectionUtils.isCompatible(Float.class, short.class), false);
assertEquals("float -> int", ReflectionUtils.isCompatible(Float.class, int.class), false);
assertEquals("float -> long", ReflectionUtils.isCompatible(Float.class, long.class), false);
assertEquals("float -> float", ReflectionUtils.isCompatible(Float.class, float.class), true);
assertEquals("float -> double", ReflectionUtils.isCompatible(Float.class, double.class), true);
assertEquals("float -> boolean", ReflectionUtils.isCompatible(Float.class, boolean.class), false);
// test float conversions
assertEquals("double -> char", ReflectionUtils.isCompatible(Double.class, char.class), false);
assertEquals("double -> byte", ReflectionUtils.isCompatible(Double.class, byte.class), false);
assertEquals("double -> short", ReflectionUtils.isCompatible(Double.class, short.class), false);
assertEquals("double -> int", ReflectionUtils.isCompatible(Double.class, int.class), false);
assertEquals("double -> long", ReflectionUtils.isCompatible(Double.class, long.class), false);
assertEquals("double -> float", ReflectionUtils.isCompatible(Double.class, float.class), false);
assertEquals("double -> double", ReflectionUtils.isCompatible(Double.class, double.class), true);
assertEquals("double -> boolean", ReflectionUtils.isCompatible(Double.class, boolean.class), false);
// test float conversions
assertEquals("boolean -> char", ReflectionUtils.isCompatible(Boolean.class, char.class), false);
assertEquals("boolean -> byte", ReflectionUtils.isCompatible(Boolean.class, byte.class), false);
assertEquals("boolean -> short", ReflectionUtils.isCompatible(Boolean.class, short.class), false);
assertEquals("boolean -> int", ReflectionUtils.isCompatible(Boolean.class, int.class), false);
assertEquals("boolean -> long", ReflectionUtils.isCompatible(Boolean.class, long.class), false);
assertEquals("boolean -> float", ReflectionUtils.isCompatible(Boolean.class, float.class), false);
assertEquals("boolean -> double", ReflectionUtils.isCompatible(Boolean.class, double.class), false);
assertEquals("boolean -> boolean", ReflectionUtils.isCompatible(Boolean.class, boolean.class), true);
}
}

View File

@ -1,127 +0,0 @@
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Bean with examples of different scoped fields and methods.
*/
public class ScopeBean {
private int privateField;
int packageField;
protected int protectedField;
public int publicField;
public static int staticField;
public final int finalField = 42;
public ScopeBean() {}
private void privateMethod() {}
protected void protectedMethod() {}
void packageMethod() {}
public void publicMethod() {}
public static void staticMethod() {}
public final void finalMethod() {}
public Field getPrivateField() throws NoSuchFieldException {
return ScopeBean.class.getDeclaredField("privateField");
}
public Field getProtectedField() throws NoSuchFieldException {
return ScopeBean.class.getDeclaredField("protectedField");
}
public Field getPackageField() throws NoSuchFieldException {
return ScopeBean.class.getDeclaredField("packageField");
}
public Field getPublicField() throws NoSuchFieldException {
return ScopeBean.class.getDeclaredField("publicField");
}
public Field getStaticField() throws NoSuchFieldException {
return ScopeBean.class.getDeclaredField("staticField");
}
public Field getFinalField() throws NoSuchFieldException {
return ScopeBean.class.getDeclaredField("finalField");
}
public Method getPrivateMethod() throws NoSuchMethodException {
return ScopeBean.class.getDeclaredMethod("privateMethod", null);
}
public Method getProtectedMethod() throws NoSuchMethodException {
return ScopeBean.class.getDeclaredMethod("protectedMethod", null);
}
public Method getPackageMethod() throws NoSuchMethodException {
return ScopeBean.class.getDeclaredMethod("packageMethod", null);
}
public Method getPublicMethod() throws NoSuchMethodException {
return ScopeBean.class.getDeclaredMethod("publicMethod", null);
}
public Method getStaticMethod() throws NoSuchMethodException {
return ScopeBean.class.getDeclaredMethod("staticMethod", null);
}
public Method getFinalMethod() throws NoSuchMethodException {
return ScopeBean.class.getDeclaredMethod("finalMethod", null);
}
}

View File

@ -1,506 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/Attic/TestBean.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* General purpose test bean for JUnit tests for the "beanutils" component.
*
* @author Craig R. McClanahan
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
public class TestBean {
// ------------------------------------------------------------- Properties
/**
* A boolean property.
*/
private boolean booleanProperty = true;
public boolean getBooleanProperty() {
return (booleanProperty);
}
public void setBooleanProperty(boolean booleanProperty) {
this.booleanProperty = booleanProperty;
}
/**
* A boolean property that uses an "is" method for the getter.
*/
private boolean booleanSecond = true;
public boolean isBooleanSecond() {
return (booleanSecond);
}
public void setBooleanSecond(boolean booleanSecond) {
this.booleanSecond = booleanSecond;
}
/**
* A double property.
*/
private double doubleProperty = 321.0;
public double getDoubleProperty() {
return (this.doubleProperty);
}
public void setDoubleProperty(double doubleProperty) {
this.doubleProperty = doubleProperty;
}
/**
* An "indexed property" accessible via both array and subscript
* based getters and setters.
*/
private String dupProperty[] =
{ "Dup 0", "Dup 1", "Dup 2", "Dup 3", "Dup 4" };
public String[] getDupProperty() {
return (this.dupProperty);
}
public String getDupProperty(int index) {
return (this.dupProperty[index]);
}
public void setDupProperty(int index, String value) {
this.dupProperty[index] = value;
}
public void setDupProperty(String dupProperty[]) {
this.dupProperty = dupProperty;
}
/**
* A float property.
*/
private float floatProperty = (float) 123.0;
public float getFloatProperty() {
return (this.floatProperty);
}
public void setFloatProperty(float floatProperty) {
this.floatProperty = floatProperty;
}
/**
* An integer array property accessed as an array.
*/
private int intArray[] = { 0, 10, 20, 30, 40 };
public int[] getIntArray() {
return (this.intArray);
}
public void setIntArray(int intArray[]) {
this.intArray = intArray;
}
/**
* An integer array property accessed as an indexed property.
*/
private int intIndexed[] = { 0, 10, 20, 30, 40 };
public int getIntIndexed(int index) {
return (intIndexed[index]);
}
public void setIntIndexed(int index, int value) {
intIndexed[index] = value;
}
/**
* An integer property.
*/
private int intProperty = 123;
public int getIntProperty() {
return (this.intProperty);
}
public void setIntProperty(int intProperty) {
this.intProperty = intProperty;
}
/**
* A List property accessed as an indexed property.
*/
private static List listIndexed = new ArrayList();
static {
listIndexed.add("String 0");
listIndexed.add("String 1");
listIndexed.add("String 2");
listIndexed.add("String 3");
listIndexed.add("String 4");
}
public List getListIndexed() {
return (listIndexed);
}
/**
* A long property.
*/
private long longProperty = 321;
public long getLongProperty() {
return (this.longProperty);
}
public void setLongProperty(long longProperty) {
this.longProperty = longProperty;
}
/**
* A mapped property with only a getter and setter for a Map.
*/
private Map mapProperty = null;
public Map getMapProperty() {
// Create the map the very first time
if (mapProperty == null) {
mapProperty = new HashMap();
mapProperty.put("First Key", "First Value");
mapProperty.put("Second Key", "Second Value");
}
return (mapProperty);
}
public void setMapProperty(Map mapProperty) {
// Create the map the very first time
if (mapProperty == null) {
mapProperty = new HashMap();
mapProperty.put("First Key", "First Value");
mapProperty.put("Second Key", "Second Value");
}
this.mapProperty = mapProperty;
}
/**
* A mapped property that has String keys and Object values.
*/
private HashMap mappedObjects = null;
public Object getMappedObjects(String key) {
// Create the map the very first time
if (mappedObjects == null) {
mappedObjects = new HashMap();
mappedObjects.put("First Key", "First Value");
mappedObjects.put("Second Key", "Second Value");
}
return (mappedObjects.get(key));
}
public void setMappedObjects(String key, Object value) {
// Create the map the very first time
if (mappedObjects == null) {
mappedObjects = new HashMap();
mappedObjects.put("First Key", "First Value");
mappedObjects.put("Second Key", "Second Value");
}
mappedObjects.put(key, value);
}
/**
* A mapped property that has String keys and String values.
*/
private HashMap mappedProperty = null;
public String getMappedProperty(String key) {
// Create the map the very first time
if (mappedProperty == null) {
mappedProperty = new HashMap();
mappedProperty.put("First Key", "First Value");
mappedProperty.put("Second Key", "Second Value");
}
return ((String) mappedProperty.get(key));
}
public void setMappedProperty(String key, String value) {
// Create the map the very first time
if (mappedProperty == null) {
mappedProperty = new HashMap();
mappedProperty.put("First Key", "First Value");
mappedProperty.put("Second Key", "Second Value");
}
mappedProperty.put(key, value);
}
/**
* A mapped property that has String keys and int values.
*/
private HashMap mappedIntProperty = null;
public int getMappedIntProperty(String key) {
// Create the map the very first time
if (mappedProperty == null) {
mappedProperty = new HashMap();
mappedProperty.put("One", new Integer(1));
mappedProperty.put("Two", new Integer(2));
}
Integer x = (Integer) mappedIntProperty.get(key);
return ((x == null) ? 0 : x.intValue());
}
public void setMappedIntProperty(String key, int value) {
mappedIntProperty.put(key, new Integer(value));
}
/**
* A nested reference to another test bean (populated as needed).
*/
private TestBean nested = null;
public TestBean getNested() {
if (nested == null)
nested = new TestBean();
return (nested);
}
/*
* Another nested reference to a bean containing mapp properties
*/
class MappedTestBean {
public void setValue(String key,String val) { }
public String getValue(String key) { return "Mapped Value"; }
}
private MappedTestBean mappedNested = null;
public MappedTestBean getMappedNested() {
if (mappedNested == null)
{
mappedNested = new MappedTestBean();
}
return mappedNested;
}
/**
* A String property with an initial value of null.
*/
private String nullProperty = null;
public String getNullProperty() {
return (this.nullProperty);
}
public void setNullProperty(String nullProperty) {
this.nullProperty = nullProperty;
}
/**
* A read-only String property.
*/
private String readOnlyProperty = "Read Only String Property";
public String getReadOnlyProperty() {
return (this.readOnlyProperty);
}
/**
* A short property.
*/
private short shortProperty = (short) 987;
public short getShortProperty() {
return (this.shortProperty);
}
public void setShortProperty(short shortProperty) {
this.shortProperty = shortProperty;
}
/**
* A String array property accessed as a String.
*/
private String stringArray[] =
{ "String 0", "String 1", "String 2", "String 3", "String 4" };
public String[] getStringArray() {
return (this.stringArray);
}
public void setStringArray(String stringArray[]) {
this.stringArray = stringArray;
}
/**
* A String array property accessed as an indexed property.
*/
private String stringIndexed[] =
{ "String 0", "String 1", "String 2", "String 3", "String 4" };
public String getStringIndexed(int index) {
return (stringIndexed[index]);
}
public void setStringIndexed(int index, String value) {
stringIndexed[index] = value;
}
/**
* A String property.
*/
private String stringProperty = "This is a string";
public String getStringProperty() {
return (this.stringProperty);
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
/**
* A write-only String property.
*/
private String writeOnlyProperty = "Write Only String Property";
public String getWriteOnlyPropertyValue() {
return (this.writeOnlyProperty);
}
public void setWriteOnlyProperty(String writeOnlyProperty) {
this.writeOnlyProperty = writeOnlyProperty;
}
// ------------------------------------------------------- Static Variables
/**
* A static variable that is accessed and updated via static methods
* for MethodUtils testing.
*/
private static int counter = 0;
/**
* Return the current value of the counter.
*/
public static int currentCounter() {
return (counter);
}
/**
* Increment the current value of the counter by 1.
*/
public static void incrementCounter() {
incrementCounter(1);
}
/**
* Increment the current value of the counter by the specified amount.
*
* @param amount Amount to be added to the current counter
*/
public static void incrementCounter(int amount) {
counter += amount;
}
}

View File

@ -1,114 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PackageBean.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* <p>This class is designed to test the default access jvm problem workaround.
* The issue is that public methods of a public subclass contained in a default access
* superclass are returned by reflection but an IllegalAccessException is thrown
* when they are invoked.</p>
*
* <p>This is the default access superclass</p>
*
* @author Robert Burrell Donkin
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
class PackageBean {
// ----------------------------------------------------------- Constructors
/**
* Package private constructor - can only use factory method to create
* beans.
*/
PackageBean() {
super();
}
// ------------------------------------------------------------- Properties
/**
*/
private String bar = "This is bar";
public String getBar() {
return (this.bar);
}
public void setBar(String bar) {
this.bar = bar;
}
}

View File

@ -1,155 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PrivateBean.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* Bean that has a private constructor that exposes properties via
* various mechanisms (based on property name):
* <ul>
* <li><strong>foo</strong> - Via direct public method
* <li><strong>bar</strong> - Via directly implemented interface
* <li><strong>baz</strong> - Via indirectly implemented interface
* </ul>
*
* @author Craig R. McClanahan
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
class PrivateBean implements PrivateDirect {
// ----------------------------------------------------------- Constructors
/**
* Package private constructor - can only use factory method to create
* beans.
*/
PrivateBean() {
super();
}
// ------------------------------------------------------------- Properties
/**
* A directly implemented property.
*/
private String foo = "This is foo";
public String getFoo() {
return (this.foo);
}
/**
* A property accessible via a directly implemented interface.
*/
private String bar = "This is bar";
public String getBar() {
return (this.bar);
}
/**
* A method accessible via a directly implemented interface.
*/
public String methodBar(String in) {
return (in);
}
/**
* A property accessible via an indirectly implemented interface.
*/
private String baz = "This is baz";
public String getBaz() {
return (this.baz);
}
/**
* A method accessible via an indirectly implemented interface.
*/
public String methodBaz(String in) {
return (in);
}
}

View File

@ -1,97 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PrivateBeanFactory.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* Factory class for PrivateBean instances.
*
* @author Craig R. McClanahan
* @author Jan Sorensen
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
public class PrivateBeanFactory {
/**
* Factory method to create new beans.
*/
public static PrivateDirect create() {
return (new PrivateBean());
}
/**
* Factory method to create new beans.
*/
public static PrivateDirect createSubclass() {
return (new PrivateBeanSubclass());
}
}

View File

@ -1,103 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PrivateBeanSubclass.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* Bean that exposes methods defined by an interface that is implemented
* in the superclass.
*
* @author Jan Sorensen
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
class PrivateBeanSubclass extends PrivateBean {
// ----------------------------------------------------------- Constructors
/**
* Create a new PrivateBeanSubclass instance.
*/
PrivateBeanSubclass() {
super();
}
// ------------------------------------------------------------- Properties
/**
* A property accessible via the superclass.
*/
public String getBar() {
return (super.getBar());
}
}

View File

@ -1,90 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PrivateDirect.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* Interface that is directly implemented by PrivateBean.
*
* @author Craig R. McClanahan
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
public interface PrivateDirect extends PrivateIndirect {
// ------------------------------------------------------------- Properties
/**
* A property accessible via a directly implemented interface.
*/
String getBar();
/**
* A method accessible via a directly implemented interface.
*/
String methodBar(String in);
}

View File

@ -1,91 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PrivateIndirect.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* Interface that is indirectly implemented by PrivateBean.
*
* @author Craig R. McClanahan
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
public interface PrivateIndirect {
// ------------------------------------------------------------- Properties
/**
* A property accessible via an indirectly implemented interface.
*/
public String getBaz();
/**
* A method accessible via an indirectly implemented interface.
*/
public String methodBaz(String in);
}

View File

@ -1,114 +0,0 @@
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//lang/src/test/org/apache/commons/lang/reflect/priv/Attic/PublicSubBean.java,v 1.2 2003/08/18 02:22:28 bayard Exp $
* $Revision: 1.2 $
* $Date: 2003/08/18 02:22:28 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.lang.reflect.priv;
/**
* <p>This class is designed to test the default access jvm problem workaround.
* The issue is that public methods of a public subclass contained in a default access
* superclass are returned by reflection but an IllegalAccessException is thrown
* when they are invoked.</p>
*
* <p>This is the default access superclass</p>
*
* @author Robert Burrell Donkin
* @version $Revision: 1.2 $ $Date: 2003/08/18 02:22:28 $
*/
public class PublicSubBean extends PackageBean {
// ----------------------------------------------------------- Constructors
/**
* Package private constructor - can only use factory method to create
* beans.
*/
public PublicSubBean() {
super();
}
// ------------------------------------------------------------- Properties
/**
* A directly implemented property.
*/
private String foo = "This is foo";
public String getFoo() {
return (this.foo);
}
public void setFoo(String foo) {
this.foo = foo;
}
}