Java tutorial
//package com.java2s; /* * Copyright 2002-2015 the original author or authors. * * 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. */ public class Main { /** * Determine the common ancestor of the given classes, if any. * * @param clazz1 the class to introspect * @param clazz2 the other class to introspect * @return the common ancestor (i.e. common superclass, one interface * extending the other), or {@code null} if none found. If any of the * given classes is {@code null}, the other class will be returned. * @since 3.2.6 */ public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2) { if (clazz1 == null) { return clazz2; } if (clazz2 == null) { return clazz1; } if (clazz1.isAssignableFrom(clazz2)) { return clazz1; } if (clazz2.isAssignableFrom(clazz1)) { return clazz2; } Class<?> ancestor = clazz1; do { ancestor = ancestor.getSuperclass(); if (ancestor == null || Object.class.equals(ancestor)) { return null; } } while (!ancestor.isAssignableFrom(clazz2)); return ancestor; } }