Java Tutorial/Reflection/Class
Содержание
- 1 Class comparator: compare and sort classes and their superclasses.
- 2 Create new instance
- 3 Demonstrates Dynamic class type checking
- 4 Demonstrates fetching nested class info from a Class object
- 5 Demonstrates getting immediate superclass info
- 6 Demonstrates how to get declaration information on a Class
- 7 Demonstrates how to set public field objects
- 8 Demonstrates the use of getDeclaringClass()
- 9 Demonstrates the use of instance comparisons
- 10 Demonstrates usage of various class information methods
- 11 Demonstration of how to obtain instances of java.lang.Class
- 12 Determine whether the supplied string represents a well-formed fully-qualified Java classname.
- 13 Get Canonical Name for a class
- 14 get class from an object
- 15 Get class name for various object
- 16 Is the Same Signature
- 17 Is Type Compatible
- 18 Returns the name of a class without the package name
Class comparator: compare and sort classes and their superclasses.
<source lang="java">
/*
* JCommon : a free general purpose class library for the Java(tm) platform * * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * ClassComparator.java * -------------------- * (C)opyright 2003-2005, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner (taquera@sherito.org); * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: ClassComparator.java,v 1.3 2005/10/18 13:24:19 mungady Exp $ * * Changes * ------- * 02-May-2003 : Initial version * */
import java.io.Serializable; import java.util.ruparator; /**
* The class comparator can be used to compare and sort classes and their * superclasses. The comparator is not able to compare classes which have no * relation... * * @author Thomas Morgner */
public class ClassComparator implements Comparator, Serializable {
/** For serialization. */ private static final long serialVersionUID = -5225335361837391120L; /** * Defaultconstructor. */ public ClassComparator() { super(); } /** * Compares its two arguments for order. Returns a negative integer, zero, or * a positive integer as the first argument is less than, equal to, or greater * than the second. * * * Note: throws ClassCastException if the arguments" types prevent them from * being compared by this Comparator. And IllegalArgumentException if the * classes share no relation. * * The implementor must ensure that sgn(compare(x, y)) == * -sgn(compare(y, x)) * for all x and y. (This implies that * compare(x, y) must throw an exception if and only if * compare(y, x) throws an exception.) * * * The implementor must also ensure that the relation is transitive: * ((compare(x, y)>0) && (compare(y, z)>0)) implies * compare(x, z)>0. * * * Finally, the implementer must ensure that compare(x, y)==0 * implies that sgn(compare(x, z))==sgn(compare(y, z)) for all * z. * * * It is generally the case, but not strictly required that * (compare(x, y)==0) == (x.equals(y)). Generally speaking, any * comparator that violates this condition should clearly indicate this fact. * The recommended language is "Note: this comparator imposes orderings that * are inconsistent with equals." * * @param o1 * the first object to be compared. * @param o2 * the second object to be compared. * @return a negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ public int compare(final Object o1, final Object o2) { final Class c1 = (Class) o1; final Class c2 = (Class) o2; if (c1.equals(o2)) { return 0; } if (c1.isAssignableFrom(c2)) { return -1; } else { if (!c2.isAssignableFrom(c2)) { throw new IllegalArgumentException("The classes share no relation"); } return 1; } } /** * Checks, whether the given classes are comparable. This method will return * true, if one of the classes is assignable from the other class. * * @param c1 * the first class to compare * @param c2 * the second class to compare * @return true, if the classes share a direct relation, false otherwise. */ public boolean isComparable(final Class c1, final Class c2) { return (c1.isAssignableFrom(c2) || c2.isAssignableFrom(c1)); }
}</source>
Create new instance
<source lang="java">
public class StringTest {
public static void main(String[] args) { try { String pc = String.class.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
}</source>
Demonstrates Dynamic class type checking
<source lang="java">
/*
* file: DynamicTypeChecking.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. * ########## DO NOT EDIT ABOVE THIS LINE ########## */
import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /**
* Demonstrates Dynamic class type checking. * * @author * @version $Revision: 1.3 $ */
public class DynamicTypeChecking {
/** * Demonstrates usage of isAssignableFrom on a class object. * * @param dataType * The data type to check. * * @return The value true if the class is a descendant of * java.lang.Number or false if it isnt. */ public static boolean isNumber(final Class dataType) { return Number.class.isAssignableFrom(dataType); } /** * Demonstration Method. * * @param args * Command Line arguments. */ public static void main(final String[] args) { final Set classes = new HashSet(); classes.add(Class.class); classes.add(Comparable.class); classes.add(Serializable.class); classes.add(Integer.class); classes.add(int.class); classes.add(Float[].class); classes.add(String.class); classes.add(double[].class); classes.add(boolean.class); System.out.println("Using isAssignableFrom:"); useAssignable(classes); System.out.println("\nUsing isInstance:"); useIsInstance(classes); } /** * Demonstrates use of isAssignableFrom on objects in a set. * * @param inputSet * The set to check. */ public static void useAssignable(final Set inputSet) { final Iterator iter = inputSet.iterator(); Object obj = null; while (iter.hasNext()) { obj = iter.next(); if (obj != null) { if (Number.class.isAssignableFrom(obj.getClass())) { System.out.println(obj); } } } } /** * Demonstrates usage of isInstance on objects in a set. * * @param inputSet * The set to check. */ public static void useIsInstance(final Set inputSet) { final Iterator iter = inputSet.iterator(); Object obj = null; while (iter.hasNext()) { obj = iter.next(); if (Number.class.isInstance(obj)) { System.out.println(obj); } } } /** * Demonstration method for class comparison based on passed class and object. * * @param dataType * The data type to check. * @param inputSet * The input set to check. * * @throws NullPointerException * If the data type given is null. */ public static void useIsInstance2(final Class dataType, final Set inputSet) { if (dataType == null) { throw new NullPointerException(); } final Iterator iter = inputSet.iterator(); Object obj = null; while (iter.hasNext()) { obj = iter.next(); if (dataType.isInstance(obj)) { System.out.println(obj); } } } /** * A bad version of useInstance. If you uncomment this method you will get a * compiler error. */ // public static void useIsInstance3(final Class dataType, final Set inputSet) // { // final Iterator iter = inputSet.iterator(); // Object obj = null; // while (iter.hasNext()) { // obj = iter.next(); // if (obj instanceof dataType) { // System.out.println(obj); // } // } // }
} /* ########## End of File ########## */</source>
Demonstrates fetching nested class info from a Class object
<source lang="java">
/*
* file: NestedInfoDemo.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
import java.util.Arrays; import javax.swing.JTable; /**
* Demonstrates fetching nested class info from a Class object. * * @author * @version $Revision: 1.3 $ */
public class NestedInfoDemo {
/** * Demo method. * * @param args Command line arguments. */ public static void main(final String[] args) { printMemberClasses(JTable.class); } /** * Printo out member information for a class. * * @param dataType The class to work with. */ public static void printMemberClasses(final Class dataType) { final Class[] nestedClasses = dataType.getClasses(); final Class[] declaredNestedClasses = dataType.getDeclaredClasses(); final Class[] nestedInterfaces = dataType.getInterfaces(); final Class declaringClass = dataType.getDeclaringClass(); // -- System.out.println("Member Class infor for: " + dataType.getName()); System.out.println("Nested Classes: " + Arrays.asList(nestedClasses)); System.out.println("Declared Nested Classes: " + Arrays.asList(declaredNestedClasses)); System.out.println("Interfaces: " + Arrays.asList(nestedInterfaces)); System.out.println("Declaring Class: " + declaringClass); System.out.println(); }
} /* ########## End of File ########## */</source>
Demonstrates getting immediate superclass info
<source lang="java">
/*
* file: SuperclassInfoDemo.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
import java.util.Set; import javax.swing.JDialog; /**
* Demonstrates getting immediate superclass info. * * @author * @version $Revision: 1.3 $ */
public class SuperclassInfoDemo {
/** * Demon method. * * @param args Command line arguments. */ public static void main(final String[] args) { System.out.println("JDialog --|> " + JDialog.class.getSuperclass()); System.out.println("Integer --|> " + Integer.class.getSuperclass()); System.out.println("Object --|> " + Object.class.getSuperclass()); System.out.println("int --|> " + int.class.getSuperclass()); System.out.println("int[] --|> " + int[].class.getSuperclass()); System.out.println("Set --|> " + Set.class.getSuperclass()); System.out.println("Comparable --|> " + Comparable.class.getSuperclass()); }
} /* ########## End of File ########## */</source>
Demonstrates how to get declaration information on a Class
<source lang="java">
/*
* file: DeclarationInfoDemo.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
import java.lang.reflect.Modifier; import java.util.Collection;
/**
* Demonstrates how to get declaration information on a Class. * * @author * @version $Revision: 1.3 $ */
public class DeclarationInfoDemo {
/** * Demonstration Method. * * @param args Command line arguments. */ public static void main(final String[] args) { printModifiers(Object.class); printModifiers(Float.class); printModifiers(Collection.class); printModifiers(int.class); printModifiers(String.class); } /** * Prints out the modifiers for a class. * * @param dataType The class for which to print out modifiers. */ public static void printModifiers(final Class dataType) { final int modifiers = dataType.getModifiers(); if (Modifier.isPrivate(modifiers)) { System.out.print("private "); } if (Modifier.isPrivate(modifiers)) { System.out.print("private "); } if (Modifier.isPublic(modifiers)) { System.out.print("private "); } if (Modifier.isAbstract(modifiers)) { System.out.print("abstract "); } if (Modifier.isFinal(modifiers)) { System.out.print("final "); } if (Modifier.isNative(modifiers)) { System.out.print("native "); } if (Modifier.isInterface(modifiers)) { System.out.print("interface "); } if (Modifier.isStatic(modifiers)) { System.out.print("static "); } if (Modifier.isStrict(modifiers)) { System.out.print("strict "); } if (Modifier.isSynchronized(modifiers)) { System.out.print("synchronized "); } if (Modifier.isTransient(modifiers)) { System.out.print("transient "); } if (Modifier.isVolatile(modifiers)) { System.out.print("volatile "); } System.out.println(dataType.getName()); }
} /* ########## End of File ########## */</source>
Demonstrates how to set public field objects
<source lang="java">
/*
* file: HiddenFieldModification.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. * ########## DO NOT EDIT ABOVE THIS LINE ########## */
import java.lang.reflect.Field; /**
* Demonstrates how to set public field objects. * * @author * @version $Revision: 1.3 $ */
public class HiddenFieldModification {
/** * Sets all int fields in an object to 0. * * @param obj * The object to operate on. * * @throws RuntimeException * If there is a reflection problem. */ public static void initIntFields(final Object obj) { try { Field[] fields = obj.getClass().getDeclaredFields(); for (int idx = 0; idx < fields.length; idx++) { if (fields[idx].getType() == int.class) { fields[idx].setAccessible(true); fields[idx].setInt(obj, 0); } } } catch (final IllegalAccessException ex) { throw new RuntimeException(ex); } } /** * Demo Method. * * @param args * Command line arguments. */ public static final void main(final String[] args) { Integer value = new Integer("123"); System.out.println("Before: " + value); initIntFields(value); System.out.println("After: " + value); }
} /* ########## End of File ########## */</source>
Demonstrates the use of getDeclaringClass()
<source lang="java">
/*
* file: DeclaringClassDemo.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
//package oreilly.hcj.reflection; import java.lang.reflect.Method; /**
* Demonstrates the use of getDeclaringClass(). * * @author * @version $Revision: 1.3 $ */
public class DeclaringClassDemo {
/** * Demo method. * * @param args Command line arguments. */ public static void main(final String[] args) { Method[] methods = String.class.getMethods(); for (int idx = 0; idx < methods.length; idx++) { System.out.println(methods[idx] + " declared by " + methods[idx].getDeclaringClass()); } }
} /* ########## End of File ########## */</source>
Demonstrates the use of instance comparisons
<source lang="java">
/*
* file: InstanceOfDemo.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. * ########## DO NOT EDIT ABOVE THIS LINE ########## */
import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.swing.JPanel; /**
* Demonstrates the use of instance comparisons. * * @author * @version $Revision: 1.3 $ */
public class InstanceOfDemo {
/** A set of demon objects. */ public static final Set OBJECT_SET; static { Set objectSet = new HashSet(); objectSet.add(new Integer(5)); objectSet.add(new String("Hardcore Java")); objectSet.add(new Float(22.5f)); objectSet.add(new JPanel()); objectSet.add(new Character("x")); objectSet.add(new ArrayList()); objectSet.add(new Double(354.5676)); objectSet.add(null); OBJECT_SET = Collections.unmodifiableSet(objectSet); } /** * Demo method. * * @param args * Command Line arguments. */ public static void main(final String[] args) { final Iterator iter = OBJECT_SET.iterator(); Object obj = null; while (iter.hasNext()) { obj = iter.next(); if (obj instanceof Number) { System.out.println(obj); } } }
} /* ########## End of File ########## */</source>
Demonstrates usage of various class information methods
<source lang="java">
/*
* file: ClassInfoDemo.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /**
* Demonstrates usage of various class information methods. * * @author * @version $Revision: 1.3 $ */
public class ClassInfoDemo {
/** * Demonstration Method * * @param args Demonstration Method. */ public static void main(final String[] args) { final Set classes = new HashSet(); classes.add(Class.class); classes.add(Comparable.class); classes.add(Serializable.class); classes.add(Integer.class); classes.add(int.class); classes.add(Float[].class); classes.add(String.class); classes.add(double[].class); classes.add(boolean.class); // -- System.out.println("Finding interface Class objects in the set."); Iterator iter = classes.iterator(); while (iter.hasNext()) { useIsInterface((Class)iter.next()); } System.out.println("\nFinding primitive Class objects in the set."); iter = classes.iterator(); while (iter.hasNext()) { useIsPrimitive((Class)iter.next()); } System.out.println("\nFinding array Class objects in the set."); iter = classes.iterator(); while (iter.hasNext()) { useIsArray((Class)iter.next()); } } /** * Demonstrates usage of isArray from Class. * * @param dataType The data type to check. * * @throws NullPointerException If the user passes null for dataType. */ public static void useIsArray(final Class dataType) { if (dataType == null) { throw new NullPointerException(); } if (dataType.isArray()) { System.out.print(dataType.getName()); System.out.println("\t ==> " + dataType.getComponentType()); } } /** * Demonstrates usage of isInterface from Class. * * @param dataType The data type to check. * * @throws NullPointerException If the user passes null for dataType. */ public static void useIsInterface(final Class dataType) { if (dataType == null) { throw new NullPointerException(); } if (dataType.isInterface()) { System.out.println(dataType.getName()); } } /** * Demonstrates usage of isPrimitive from Class. * * @param dataType The data type to check. * * @throws NullPointerException If the user passes null for dataType. */ public static void useIsPrimitive(final Class dataType) { if (dataType == null) { throw new NullPointerException(); } if (dataType.isPrimitive()) { System.out.println(dataType.getName()); } }
} /* ########## End of File ########## */</source>
Demonstration of how to obtain instances of java.lang.Class
<source lang="java">
/*
* file: ObtainingClassInstances.java * package: oreilly.hcj.reflection * * This software is granted under the terms of the Common Public License, * CPL, which may be found at the following URL: * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm * * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * All Rights are Reserved by the various authors. *
- DO NOT EDIT ABOVE THIS LINE ########## */
/**
* Demonstration of how to obtain instances of java.lang.Class. * * @author * @version $Revision: 1.3 $ */
public class ObtainingClassInstances {
/** An Integer object */ protected static Integer someInteger = new Integer(10); /** A generic object. */ protected static Object someObject = null; /** A String. */ protected static String someString = new String("Hardcore Java"); /** An int. */ protected static int someInt = 15; /** An array of ints. */ protected static int[] intArray = new int[] { 4, 5, 7, 9 }; /** * Main method. * * @param args Command line arguments. */ public static void main(final String[] args) { // -- Print out the Class instances. System.out.println(someInteger.getClass()); System.out.println(someString.getClass()); System.out.println(intArray.getClass()); System.out.println(Object.class); System.out.println(Integer.class); System.out.println(int.class); System.out.println(String.class); System.out.println(Comparable.class); System.out.println(Object[].class); // -- Things that WON"T work // System.out.println(someObject.getClass()); // <= Exception // System.out.println(someInt.getClass()); // <= Compiler errror } /** * Demonstration of a method that doesnt check for null. * * @param obj The object passed. */ public void writeClass(final Object obj) { System.out.println(obj.getClass()); }
} /* ########## End of File ########## */</source>
Determine whether the supplied string represents a well-formed fully-qualified Java classname.
<source lang="java">
/*
* JBoss DNA (http://www.jboss.org/dna) * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * See the AUTHORS.txt file in the distribution for a full listing of * individual contributors. * * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA * is licensed to you under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * JBoss DNA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
import java.text.CharacterIterator; import java.text.StringCharacterIterator;
public class Utils {
/** * Determine whether the supplied string represents a well-formed fully-qualified Java classname. This utility method enforces * no conventions (e.g., packages are all lowercase) nor checks whether the class is available on the classpath. * * @param classname * @return true if the string is a fully-qualified class name */ public static boolean isFullyQualifiedClassname( String classname ) { if (classname == null) return false; String[] parts = classname.split("[\\.]"); if (parts.length == 0) return false; for (String part : parts) { CharacterIterator iter = new StringCharacterIterator(part); // Check first character (there should at least be one character for each part) ... char c = iter.first(); if (c == CharacterIterator.DONE) return false; if (!Character.isJavaIdentifierStart(c) && !Character.isIdentifierIgnorable(c)) return false; c = iter.next(); // Check the remaining characters, if there are any ... while (c != CharacterIterator.DONE) { if (!Character.isJavaIdentifierPart(c) && !Character.isIdentifierIgnorable(c)) return false; c = iter.next(); } } return true; }
}</source>
Get Canonical Name for a class
<source lang="java">
public class GetCanonicalName {
public static void main(String[] args) { System.out.println(Person.class.getCanonicalName()); }
} //// import javax.ejb.Entity; import javax.ejb.AccessType; import javax.ejb.Id; import javax.ejb.GeneratorType; import java.io.Serializable; @Entity(access = AccessType.FIELD) public class Person implements Serializable {
@Id(generate = GeneratorType.AUTO) Integer id; String name;
}</source>
get class from an object
<source lang="java">
// ClassInfoDemo1.java class ClassInfoDemo1 {
public static void main (String [] args) { String s = ""; Class c = s.getClass (); System.out.println (c.getName ()); c = new ClassInfoDemo1 ().getClass (); System.out.println (c.getName ()); }
}</source>
Get class name for various object
<source lang="java">
public class GetName {
public static void main(String[] args) { System.out.println(GetName.class.getName()); System.out.println(int[].class.getName()); System.out.println(GetName[].class.getName()); System.out.println(GetName.class.getPackage()); }
}</source>
Is the Same Signature
<source lang="java">
// //$Id: IntrospectionUtil.java 1540 2007-01-19 12:24:10Z janb $ //Copyright 2006 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //
import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; public class Utils {
public static boolean isSameSignature(Method methodA, Method methodB) { if (methodA == null) return false; if (methodB == null) return false; List parameterTypesA = Arrays.asList(methodA.getParameterTypes()); List parameterTypesB = Arrays.asList(methodB.getParameterTypes()); if (methodA.getName().equals(methodB.getName()) && parameterTypesA.containsAll(parameterTypesB)) return true; return false; }
}</source>
Is Type Compatible
<source lang="java">
// //$Id: IntrospectionUtil.java 1540 2007-01-19 12:24:10Z janb $ //Copyright 2006 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //
import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; public class Utils {
public static boolean isTypeCompatible(Class formalType, Class actualType, boolean strict) { if (formalType == null && actualType != null) return false; if (formalType != null && actualType == null) return false; if (formalType == null && actualType == null) return true; if (strict) return formalType.equals(actualType); else return formalType.isAssignableFrom(actualType); }
}</source>
Returns the name of a class without the package name
<source lang="java">
public class Utils {
/** * Returns the name of a class without the package name. For example: if * input = "java.lang.Object" , then output = "Object". * @param fully qualified classname * @return the unqualified classname */ public static String getShortClassName(final String className) { if (className != null) { final int index = className.lastIndexOf("."); return className.substring(index + 1); } return null; }
}</source>