Java Tutorial/Reflection/Interface
Содержание
- 1 Although the type of o2 is an interface, getSuperclass() returns the object"s superclass
- 2 Checking whether String is an interface or class
- 3 Get all interface and object classes that are generalizations of the provided class
- 4 Get Super Interfaces
- 5 If a class object is an interface or a class
- 6 Listing the Interfaces That a Class Implements
- 7 Listing the Interfaces That an Interface Extends
- 8 Return Returns true if type is implementing Map
- 9 Returns true if a class implements Serializable and false otherwise.
- 10 The interfaces for a primitive type is an empty array
- 11 The superclass of interfaces is always null
Although the type of o2 is an interface, getSuperclass() returns the object"s superclass
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Runnable o2 = new Runnable() { public void run() { } }; Class sup = o2.getClass().getSuperclass(); // java.lang.Object }
}</source>
Checking whether String is an interface or class
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Class clazz = String.class; boolean isInterface = clazz.isInterface(); System.out.println("Is Interface = " + isInterface); }
}</source>
Get all interface and object classes that are generalizations of the provided class
<source lang="java">
/*
* The contents of this file are subject to the Sapient Public License * Version 1.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://carbon.sf.net/License.html. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Original Code is The Carbon Component Framework. * * The Initial Developer of the Original Code is Sapient Corporation * * Copyright (C) 2003 Sapient Corporation. All Rights Reserved. */
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /**
* * * Copyright 2003 Sapient * @since carbon 2.0 * @author Greg Hinkle, March 2003 * @version $Revision: 1.5 $($Author: dvoet $ / $Date: 2003/05/05 21:21:23 $) */
public class ClassUtil {
/** * Retrieves all interfaces implemented by a specified interface * including all recursively extended interfaces and the classes supplied * int the parameter. * @param childInterfaces a set of interfaces * @return Class[] an array of interfaces that includes those specifed * in childInterfaces plus all of those interfaces" super interfaces */ public static Class[] getSuperInterfaces(Class[] childInterfaces) { List allInterfaces = new ArrayList(); for (int i = 0; i < childInterfaces.length; i++) { allInterfaces.add(childInterfaces[i]); allInterfaces.addAll( Arrays.asList( getSuperInterfaces(childInterfaces[i].getInterfaces()))); } return (Class[]) allInterfaces.toArray(new Class[allInterfaces.size()]); } /** * Builds an unordered set of all interface and object classes that * are generalizations of the provided class. * @param classObject the class to find generalization of. * @return a Set of class objects. */ public static Set getGeneralizations(Class classObject) { Set generalizations = new HashSet(); generalizations.add(classObject); Class superClass = classObject.getSuperclass(); if (superClass != null) { generalizations.addAll(getGeneralizations(superClass)); } Class[] superInterfaces = classObject.getInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { Class superInterface = superInterfaces[i]; generalizations.addAll(getGeneralizations(superInterface)); } return generalizations; }
}</source>
Get Super Interfaces
<source lang="java">
/*
* The contents of this file are subject to the Sapient Public License * Version 1.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://carbon.sf.net/License.html. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Original Code is The Carbon Component Framework. * * The Initial Developer of the Original Code is Sapient Corporation * * Copyright (C) 2003 Sapient Corporation. All Rights Reserved. */
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /**
* * * Copyright 2003 Sapient * @since carbon 2.0 * @author Greg Hinkle, March 2003 * @version $Revision: 1.5 $($Author: dvoet $ / $Date: 2003/05/05 21:21:23 $) */
public class ClassUtil {
/** * Retrieves all interfaces implemented by a specified interface * including all recursively extended interfaces and the classes supplied * int the parameter. * @param childInterfaces a set of interfaces * @return Class[] an array of interfaces that includes those specifed * in childInterfaces plus all of those interfaces" super interfaces */ public static Class[] getSuperInterfaces(Class[] childInterfaces) { List allInterfaces = new ArrayList(); for (int i = 0; i < childInterfaces.length; i++) { allInterfaces.add(childInterfaces[i]); allInterfaces.addAll( Arrays.asList( getSuperInterfaces(childInterfaces[i].getInterfaces()))); } return (Class[]) allInterfaces.toArray(new Class[allInterfaces.size()]); } /** * Builds an unordered set of all interface and object classes that * are generalizations of the provided class. * @param classObject the class to find generalization of. * @return a Set of class objects. */ public static Set getGeneralizations(Class classObject) { Set generalizations = new HashSet(); generalizations.add(classObject); Class superClass = classObject.getSuperclass(); if (superClass != null) { generalizations.addAll(getGeneralizations(superClass)); } Class[] superInterfaces = classObject.getInterfaces(); for (int i = 0; i < superInterfaces.length; i++) { Class superInterface = superInterfaces[i]; generalizations.addAll(getGeneralizations(superInterface)); } return generalizations; }
}</source>
If a class object is an interface or a class
<source lang="java">
public class Main {
public static void main(String[] args) { // Checking whether Cloneable is an interface or class Class clazz = Cloneable.class; boolean isInterface = clazz.isInterface(); System.out.println("Is Interface = " + isInterface); }
}</source>
Listing the Interfaces That a Class Implements
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Class cls = java.lang.String.class; Class[] intfs = cls.getInterfaces(); }
}</source>
Listing the Interfaces That an Interface Extends
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Class cls = java.util.List.class; Class[] intfs = cls.getInterfaces(); // java.util.Collection }
}</source>
Return Returns true if type is implementing Map
<source lang="java">
// $Id: ReflectionHelper.java 16271 2009-04-07 20:20:12Z hardy.ferentschik $ /*
- JBoss, Home of Professional Open Source
- Copyright 2008, Red Hat Middleware LLC, and individual contributors
- by the @authors tag. See the copyright.txt in the distribution for a
- full listing of individual contributors.
- 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.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; /**
* Some reflection utility methods. * * @author Hardy Ferentschik */
public class ReflectionHelper {
/** * @param type the type to check. * * @return Returnstrue
iftype
is implementingMap
,false
otherwise. */ public static boolean isMap(Type type) { if ( type instanceof Class && isMapClass( ( Class ) type ) ) { return true; } if ( type instanceof ParameterizedType ) { return isMap( ( ( ParameterizedType ) type ).getRawType() ); } if ( type instanceof WildcardType ) { Type[] upperBounds = ( ( WildcardType ) type ).getUpperBounds(); return upperBounds.length != 0 && isMap( upperBounds[0] ); } return false; } /** * Checks whether the specified class parameter is an instance of a collection class. * * @param clazzClass
to check. * * @returntrue
isclazz
is instance of a collection class,false
otherwise. */ private static boolean isMapClass(Class<?> clazz) { List<Class<?>> classes = new ArrayList<Class<?>>(); computeClassHierarchy( clazz, classes ); return classes.contains( Map.class ); } /** * Get all superclasses and interfaces recursively. * * @param clazz The class to start the search with. * @param classes List of classes to which to add all found super classes and interfaces. */ private static void computeClassHierarchy(Class<?> clazz, List<Class<?>> classes) { for ( Class current = clazz; current != null; current = current.getSuperclass() ) { if ( classes.contains( current ) ) { return; } classes.add( current ); for ( Class currentInterface : current.getInterfaces() ) { computeClassHierarchy( currentInterface, classes ); } } }
}</source>
Returns true if a class implements Serializable and false otherwise.
<source lang="java">
import java.io.Serializable; /*
* 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.] * * ------------ * IOUtils.java * ------------ * (C)opyright 2002-2004, by Thomas Morgner and Contributors. * * Original Author: Thomas Morgner; * Contributor(s): David Gilbert (for Object Refinery Limited); * * $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $ * * Changes * ------- * 26-Jan-2003 : Initial version * 23-Feb-2003 : Documentation * 25-Feb-2003 : Fixed Checkstyle issues (DG); * 29-Apr-2003 : Moved to jcommon * 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL; * added support for query strings within these urls (TM); */
public class Main {
/** * Returnstrue
if a class implementsSerializable
* andfalse
otherwise. * * @param c the class. * * @return A boolean. */ public static boolean isSerializable(final Class c) { /** final Class[] interfaces = c.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].equals(Serializable.class)) { return true; } } Class cc = c.getSuperclass(); if (cc != null) { return isSerializable(cc); } */ return (Serializable.class.isAssignableFrom(c)); }
}</source>
The interfaces for a primitive type is an empty array
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Class cls = int.class; Class[] intfs = cls.getInterfaces(); // [] }
}</source>
The superclass of interfaces is always null
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Class cls = java.lang.Cloneable.class; Class sup = cls.getSuperclass(); // null }
}</source>