alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (JClass.java)

This example Java source code file (JClass.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

arraylist, empty_array, iterator, jarrayclass, jclass, jcodemodel, jfieldref, jinvocation, jnarrowedclass, jprimitivetype, jtypevar, jtypewildcard, list, string, util

The JClass.java Java example source code

/*
 * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code 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 General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package com.sun.codemodel.internal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Represents a Java reference type, such as a class, an interface,
 * an enum, an array type, a parameterized type.
 *
 * <p>
 * To be exact, this object represents an "use" of a reference type,
 * not necessarily a declaration of it, which is modeled as {@link JDefinedClass}.
 */
public abstract class JClass extends JType
{
    protected JClass( JCodeModel _owner ) {
        this._owner = _owner;
    }

    /**
     * Gets the name of this class.
     *
     * @return
     *  name of this class, without any qualification.
     *  For example, this method returns "String" for
     *  <code>java.lang.String.
     */
    abstract public String name();

        /**
     * Gets the package to which this class belongs.
     * TODO: shall we move move this down?
     */
    abstract public JPackage _package();

    /**
     * Returns the class in which this class is nested, or <tt>null if
     * this is a top-level class.
     */
    public JClass outer() {
        return null;
    }

    private final JCodeModel _owner;
    /** Gets the JCodeModel object to which this object belongs. */
    public final JCodeModel owner() { return _owner; }

    /**
     * Gets the super class of this class.
     *
     * @return
     *      Returns the JClass representing the superclass of the
     *      entity (class or interface) represented by this {@link JClass}.
     *      Even if no super class is given explicitly or this {@link JClass}
     *      is not a class, this method still returns
     *      {@link JClass} for {@link Object}.
     *      If this JClass represents {@link Object}, return null.
     */
    abstract public JClass _extends();

    /**
     * Iterates all super interfaces directly implemented by
     * this class/interface.
     *
     * @return
     *          A non-null valid iterator that iterates all
     *          {@link JClass} objects that represents those interfaces
     *          implemented by this object.
     */
    abstract public Iterator<JClass> _implements();

    /**
     * Iterates all the type parameters of this class/interface.
     *
     * <p>
     * For example, if this {@link JClass} represents
     * <code>Set<T>, this method returns an array
     * that contains single {@link JTypeVar} for 'T'.
     */
    public JTypeVar[] typeParams() {
        return EMPTY_ARRAY;
    }

    /**
     * Sometimes useful reusable empty array.
     */
    protected static final JTypeVar[] EMPTY_ARRAY = new JTypeVar[0];

    /**
     * Checks if this object represents an interface.
     */
    abstract public boolean isInterface();

    /**
     * Checks if this class is an abstract class.
     */
    abstract public boolean isAbstract();

    /**
     * If this class represents one of the wrapper classes
     * defined in the java.lang package, return the corresponding
     * primitive type. Otherwise null.
     */
    public JPrimitiveType getPrimitiveType() { return null; }

    /**
     * @deprecated calling this method from {@link JClass}
     * would be meaningless, since it's always guaranteed to
     * return <tt>this.
     */
    public JClass boxify() { return this; }

    public JType unboxify() {
        JPrimitiveType pt = getPrimitiveType();
        return pt==null ? (JType)this : pt;
    }

    public JClass erasure() {
        return this;
    }

    /**
     * Checks the relationship between two classes.
     * <p>
     * This method works in the same way as {@link Class#isAssignableFrom(Class)}
     * works. For example, baseClass.isAssignableFrom(derivedClass)==true.
     */
    public final boolean isAssignableFrom( JClass derived ) {
        // to avoid the confusion, always use "this" explicitly in this method.

        // null can be assigned to any type.
        if( derived instanceof JNullType )  return true;

        if( this==derived )     return true;

        // the only class that is assignable from an interface is
        // java.lang.Object
        if( this==_package().owner().ref(Object.class) )  return true;

        JClass b = derived._extends();
        if( b!=null && this.isAssignableFrom(b) )
            return true;

        if( this.isInterface() ) {
            Iterator<JClass> itfs = derived._implements();
            while( itfs.hasNext() )
                if( this.isAssignableFrom(itfs.next()) )
                    return true;
        }

        return false;
    }

    /**
     * Gets the parameterization of the given base type.
     *
     * <p>
     * For example, given the following
     * <pre>
     * interface Foo&lt;T&gt; extends List<List<T>> {}
     * interface Bar extends Foo&lt;String&gt; {}
     * &lt;/xmp&gt;</pre>
     * This method works like this:
     * &lt;pre&gt;<xmp>
     * getBaseClass( Bar, List ) = List&lt;List<String&gt;
     * getBaseClass( Bar, Foo  ) = Foo&lt;String&gt;
     * getBaseClass( Foo&lt;? extends Number&gt;, Collection ) = Collection<List<? extends Number>>
     * getBaseClass( ArrayList&lt;? extends BigInteger&gt;, List ) = List<? extends BigInteger>
     * &lt;/xmp&gt;</pre>
     *
     * @param baseType
     *      The class whose parameterization we are interested in.
     * @return
     *      The use of {@code baseType} in {@code this} type.
     *      or null if the type is not assignable to the base type.
     */
    public final JClass getBaseClass( JClass baseType ) {

        if( this.erasure().equals(baseType) )
            return this;

        JClass b = _extends();
        if( b!=null ) {
            JClass bc = b.getBaseClass(baseType);
            if(bc!=null)
                return bc;
        }

        Iterator&lt;JClass&gt; itfs = _implements();
        while( itfs.hasNext() ) {
            JClass bc = itfs.next().getBaseClass(baseType);
            if(bc!=null)
                return bc;
        }

        return null;
    }

    public final JClass getBaseClass( Class&lt;?&gt; baseType ) {
        return getBaseClass(owner().ref(baseType));
    }


    private JClass arrayClass;
    public JClass array() {
        if(arrayClass==null)
            arrayClass = new JArrayClass(owner(),this);
        return arrayClass;
    }

    /**
     * "Narrows" a generic class to a concrete class by specifying
     * a type argument.
     *
     * &lt;p&gt;
     * &lt;code&gt;.narrow(X)</code> builds <code>Set&lt;X></code> from <code>Set</code>.
     */
    public JClass narrow( Class&lt;?&gt; clazz ) {
        return narrow(owner().ref(clazz));
    }

    public JClass narrow( Class&lt;?&gt;... clazz ) {
        JClass[] r = new JClass[clazz.length];
        for( int i=0; i&lt;clazz.length; i++ )
            r[i] = owner().ref(clazz[i]);
        return narrow(r);
    }

    /**
     * "Narrows" a generic class to a concrete class by specifying
     * a type argument.
     *
     * &lt;p&gt;
     * &lt;code&gt;.narrow(X)</code> builds <code>Set&lt;X></code> from <code>Set</code>.
     */
    public JClass narrow( JClass clazz ) {
        return new JNarrowedClass(this,clazz);
    }

    public JClass narrow( JType type ) {
        return narrow(type.boxify());
    }

    public JClass narrow( JClass... clazz ) {
        return new JNarrowedClass(this,Arrays.asList(clazz.clone()));
    }

    public JClass narrow( List&lt;? extends JClass&gt; clazz ) {
        return new JNarrowedClass(this,new ArrayList&lt;JClass&gt;(clazz));
    }

    /**
     * If this class is parameterized, return the type parameter of the given index.
     */
    public List&lt;JClass&gt; getTypeParameters() {
        return Collections.emptyList();
    }

    /**
     * Returns true if this class is a parameterized class.
     */
    public final boolean isParameterized() {
        return erasure()!=this;
    }

    /**
     * Create "? extends T" from T.
     *
     * @return never null
     */
    public final JClass wildcard() {
        return new JTypeWildcard(this);
    }

    /**
     * Substitutes the type variables with their actual arguments.
     *
     * &lt;p&gt;
     * For example, when this class is Map&lt;String,Map&lt;V&gt;>,
     * (where V then doing
     * substituteParams( V, Integer ) returns a {@link JClass}
     * for &lt;code&gt;Map&lt;String,Map&lt;Integer>></code>.
     *
     * &lt;p&gt;
     * This method needs to work recursively.
     */
    protected abstract JClass substituteParams( JTypeVar[] variables, List&lt;JClass&gt; bindings );

    public String toString() {
        return this.getClass().getName() + '(' + name() + ')';
    }


    public final JExpression dotclass() {
        return JExpr.dotclass(this);
    }

    /** Generates a static method invocation. */
    public final JInvocation staticInvoke(JMethod method) {
        return new JInvocation(this,method);
    }

    /** Generates a static method invocation. */
    public final JInvocation staticInvoke(String method) {
        return new JInvocation(this,method);
    }

    /** Static field reference. */
    public final JFieldRef staticRef(String field) {
        return new JFieldRef(this, field);
    }

    /** Static field reference. */
    public final JFieldRef staticRef(JVar field) {
        return new JFieldRef(this, field);
    }

    public void generate(JFormatter f) {
        f.t(this);
    }

    /**
     * Prints the class name in javadoc @link format.
     */
    void printLink(JFormatter f) {
        f.p("{@link ").g(this).p('}');
    }
}
</pre>
<div id="after_source_code">
<h2>Other Java examples (source code examples)</h2>
<p>Here is a short list of links related to this Java JClass.java source code file:</p>
<ul>
  <li><a href="/java/jwarehouse"><img src="/images/scw/find.png" border="0">&nbsp;The search page</a></li>
  <li><a href="index.shtml"><img src="/images/scw/folder.png" border="0">&nbsp;Other Java source code examples at this package level</a></li>
  <li><a href="/java/jwarehouse/about.shtml"><img src="/images/scw/information.png" border="0">&nbsp;Click here to learn more about this project</a></li>
</ul>
</div>
</td>
</tr>
</table>
</div>
</div>

<div style="padding-top: 1em; width: 310px; margin-left: auto; margin-right: auto; table {border-collapse: collapse; border: none;}; tr {border-collapse: collapse; border: none; text-align: center;};">
<table width="100%" cellspacing="0" cellpadding="0">
  <tr>
      <td colspan="2" style="border-collapse: collapse; border: none; text-align: center;};">
        <em>... this post is sponsored by my books ...</em>
      </td>
  </tr>
  <tr>
      <td width="150" style="border-collapse: collapse; border: none; text-align: center;};">
        <a href="https://kbhr.co/ckbk-v2"><img
           src="/images/books/scala-cookbook-v2-cover-220h.jpg"
           title="The Scala Cookbook, by Alvin Alexander" height="220" />
           <br /><span style="opacity: 0.4;">#1 New Release!</span></a>
      </td>
      <td width="150" style="border-collapse: collapse; border: none; text-align: center; padding-left: 8px;">
        <a href="http://kbhr.co/fps-book"><img
           src="/images/books/functional-programming-simplified-small.jpg"
           title="Functional Programming, Simplified, by Alvin Alexander"
           height="220" />
           <br /><span style="opacity: 0.4;">FP Best Seller</span></a>
      </td>
  </tr>
</table>
<p>&nbsp;</p>
</div>


<div id="whats_new">
<h2>new blog posts</h2>
<div id="whats_new_list">
<ul>
<li><a class="whats_new_link" href="/photos/als-oasis">Al&#039;s Oasis</a></li>
<li><a class="whats_new_link" href="/photos/window-poet">Window of the Poet (painting)</a></li>
<li><a class="whats_new_link" href="/personal/ezoic-ads-vs-google-adsense-2024">Ezoic ads vs Google AdSense (2024, website advertising revenue/partner)</a></li>
<br/>
<li><a class="whats_new_link" href="/misc/dream-vacation-for-meditator-meditation">A dream vacation for the meditator in your life</a></li>
<li><a class="whats_new_link" href="/scala/zio-http-netty-AnnotatedNoRouteToHostException-null-solution">ZIO HTTP: Netty AnnotatedNoRouteToHostException null solution</a></li>
<li><a class="whats_new_link" href="/misc/inside-shinzens-brain-how-zen-master-experiences-daily-life-world-enlightened">Inside Shinzen&#039;&#039;&#039;s Brain: How A Zen Master Experiences his Daily Life</a></li>
<br/>
<li><a class="whats_new_link" href="/misc/shinzen-young-meditating-daily-life-arising-disappearing-the-source-love">Shinzen Young on meditating in his daily life: arising, disappearing, and The Source, and love</a></li>
<li><a class="whats_new_link" href="/scala/zio-zlayer-very-simple-example-dependency-injection-services">ZIO ZLayer: A simple &#039;&#039;&#039;Hello, world&#039;&#039;&#039; example (dependency injection, services)</a></li>
<li><a class="whats_new_link" href="/misc/trying-find-way-love-everyone-in-world-dont-like-dark-night-soul">Trying to find a way to love everyone in a world ...</a></li>
<br/>
<br/>
</div>
</ul>
</div>


<p>&nbsp;</p>

<p align="center"><font color="#000000" size="2"
face="Verdana,Arial">Copyright 1998-2021 Alvin Alexander, alvinalexander.com<br/>
All Rights Reserved.<br/>
<br/>
A percentage of advertising revenue from<br/>
pages under the <a href="/java/jwarehouse">/java/jwarehouse</a> 
URI on this website is<br/>
paid back to open source projects.</p>


<script>
shuffle(books);
var div = document.getElementById("leftcol");
var pre = '<div style="margin: 0; padding-right: 1.6em"><h2 align="center">favorite&nbsp;books</h2>';
var post = '</div>';
if (adblock) {
  var str = books.slice(0,3).join(" ");
  div.insertAdjacentHTML('beforeend', pre + str + post);
} else {
  var str = books.slice(0,1).join(" ");
  div.insertAdjacentHTML('beforeend', pre + str + post);
}
</script>



<p style="padding-bottom: 80px;">&nbsp;</p>


</body>