KickJava   Java API By Example, From Geeks To Geeks.

Java > Java SE, EE, ME > java > lang > Class

java.lang
Class Class<T>

java.lang.Object
  extended by java.lang.Class<T>
All Implemented Interfaces:
Serializable, AnnotatedElement, GenericDeclaration, Type
See Also:
Top Examples, Source Code, ClassLoader.defineClass(byte[], int, int)

public <U> Class<? extends U> asSubclass(Class<U> clazz)
See Also:
ClassCastException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public T cast(Object obj)
See Also:
ClassCastException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean desiredAssertionStatus()
See Also:
ClassLoader.setDefaultAssertionStatus(boolean), ClassLoader.setPackageAssertionStatus(java.lang.String, boolean), ClassLoader.setClassAssertionStatus(java.lang.String, boolean)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static Class<?> forName(String className)
                        throws ClassNotFoundException
See Also:
ExceptionInInitializerError, LinkageError
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[265]Process DB records
By Anonymous on 2005/03/15 11:30:08  Rate
//Declare a method and some variables. 
  
  
 public void ListStudents (  )  throws SQLException  {  
 int i, NoOfColumns; 
 String StNo,StFName,StLName; 
  
  
 //Initialize and load the JDBC-ODBC driver. 
 Class.forName  ( "jdbc.odbc.JdbcOdbcDriver" ) ; 
  
  
 //Make the connection object. 
 Connection Ex1Con = DriverManager.getConnection (  "jdbc:odbc:StudentDB;uid="admin";pw="sa" ) ; 
  
  
  
 //Create a simple Statement object. 
 Statement Ex1Stmt = Ex1Con.createStatement (  ) ; 
  
  
 //Make a SQL string, pass it to the DBMS, and execute the SQL statement. 
 ResultSet Ex1rs = Ex1Stmt.executeQuery ( "SELECT StudentNumber, FirstName, LastName FROM Students" ) ; 
  
  
 //Process each row until there are no more rows. 
 // Displays the results on the console. 
 System.out.println ( "Student Number First Name Last Name" ) ; 
  
  
 while  ( Ex1rs.next (  )  )   {  
  
  
     // Get the column values into Java variables 
     StNo = Ex1rs.getString ( 1 ) ; 
     StFName = Ex1rs.getString ( 2 ) ; 
     StLName = Ex1rs.getString ( 3 ) ; 
     System.out.println ( StNo,StFName,StLName ) ; 
  }  
  
  
  } 


[926]Better way to load class
By Anonymous on 2004/09/25 22:10:03  Rate
It is better to do: 
  
  
  Thread.getContextClassLoader (  ) .loadClass ( "Foo" ) ; 
   
 Than: 
   
  Class.forName ( "foo" ) ; 
  
  
 This is why, 
  
  
 Class.forName will use the ClassLoader for the current class. Whereas  
 the other uses the classloader associated with the current thread. 
  
  
 The problem is that you usually want to load classes in the thread's  
 classloader because it "knows what's going on" better. 
  
  
 For example, you write code in a jar and put it in the app server's  
 shared library location. You have a web application that calls into it with the name of a class you want to load that is defined in a jar in WEB-INF/lib. If you use Class.forName, it will fail, whereas with  
 Thread one should succeed. 
  
  
 The same thing potentially could happen with shared jars in an ear and 
 other situations. 
 


[1304]Alternative way to load class
By Anonymous on 2005/02/15 03:58:24  Rate
Another alternative is: 
  
  
   Class.forName (  "Foo", true, ClassLoader.getSystemClassLoader (  )   )  
  
  
 This behaves more like Class.forName, e.g. throws same exceptions, and has some advantages and disadvantages compared to: 
  
  
    Thread.getContextClassLoader (  ) .loadClass (  "Foo"  )  
  
  
 Both are better than: 
  
  
    Class.forName (  "Foo"  )  
  
  
 See: 
  
  
    http://www.theserverside.com/articles/content/dm_classForname/DynLoad.pdf 
  
  
 for a discussion of this issue.


[1946]What is the difference between Class.forName() and ClassLoader.loadClass()?
By Anonymous on 2007/12/07 13:50:52  Rate
Both methods try to dynamically locate and load a java.lang.Class object corresponding to a given class name. However, their behavior differs regarding which java.lang.ClassLoader they use for class loading and whether or not the resulting Class object is initialized. 
  
  
 The most common form of Class.forName (  ) , the one that takes a single String parameter, always uses the caller's classloader. This is the classloader that loads the code executing the forName (  )  method. By comparison, ClassLoader.loadClass (  )  is an instance method and requires you to select a particular classloader, which may or may not be the loader that loads that calling code. If picking a specific loader to load the class is important to your design, you should use ClassLoader.loadClass (  )  or the three-parameter version of forName (  )  added in Java 2 Platform, Standard Edition  ( J2SE ) : Class.forName ( String, boolean, ClassLoader ) . 
  
  
 Additionally, Class.forName (  ) 's common form initializes the loaded class. The visible effect of this is the execution of the class's static initializers as well as byte code corresponding to initialization expressions of all static fields  ( this process occurs recursively for all the class's superclasses ) . This differs from ClassLoader.loadClass (  )  behavior, which delays initialization until the class is used for the first time. 
  
  
 You can take advantage of the above behavioral differences. For example, if you are about to load a class you know has a very costly static initializer, you may choose to go ahead and load it to ensure it is found in the classpath but delay its initialization until the first time you need to make use of a field or method from this particular class. 
  
  
 The three-parameter method Class.forName ( String, boolean, ClassLoader )  is the most general of them all. You can delay initialization by setting the second parameter to false and pick a given classloader using the third parameter. I recommend always using this method for maximum flexibility.


public static Class<?> forName(String name,
                               boolean initialize,
                               ClassLoader loader)
                        throws ClassNotFoundException
See Also:
forName(String), ExceptionInInitializerError, LinkageError
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
See Also:
AnnotatedElement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Annotation[] getAnnotations()
See Also:
AnnotatedElement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String getCanonicalName()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Class[] getClasses()
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC), SecurityException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public ClassLoader getClassLoader()
See Also:
RuntimePermission, SecurityManager.checkPermission(java.security.Permission), SecurityException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Class<?> getComponentType()
See Also:
Array
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Constructor<T> getConstructor(Class... parameterTypes)
                              throws NoSuchMethodException,
                                     SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Constructor getConstructor(Class[] parameterTypes)
                           throws NoSuchMethodException,
                                  SecurityException
See Also:
SecurityManager.checkPackageAccess(String), SecurityManager.checkMemberAccess(Class, int)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[44]Look for the constructor that has one String parameter
By Anonymous on 2005/02/22 10:52:02  Rate
Class cl = null; 
  Constructor cnst = null; 
  
  
  cl = getClass (  ) .forName ( "MyClass" ) ; 
  //Look for the constructor that has one String parameter 
  cnst = cl.getConstructor (  new Class [  ]   {  String.class  }   ) ; 
  MyClass mc =  ( MyClass ) cnst.newInstance (  new Object [  ]   {  "A String"  }   ) ;


public Constructor[] getConstructors()
                              throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Annotation[] getDeclaredAnnotations()
See Also:
AnnotatedElement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Class[] getDeclaredClasses()
                           throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Constructor<T> getDeclaredConstructor(Class... parameterTypes)
                                      throws NoSuchMethodException,
                                             SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Constructor getDeclaredConstructor(Class[] parameterTypes)
                                   throws NoSuchMethodException,
                                          SecurityException
See Also:
SecurityManager.checkPackageAccess(String), SecurityManager.checkMemberAccess(Class, int)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Constructor[] getDeclaredConstructors()
                                      throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Field getDeclaredField(String name)
                       throws NoSuchFieldException,
                              SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED), NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Field[] getDeclaredFields()
                          throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Method getDeclaredMethod(String name,
                                Class... parameterTypes)
                         throws NoSuchMethodException,
                                SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED), NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Method getDeclaredMethod(String name,
                                Class[] parameterTypes)
                         throws NoSuchMethodException,
                                SecurityException
See Also:
SecurityManager.checkPackageAccess(String), SecurityManager.checkMemberAccess(Class, int)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Method[] getDeclaredMethods()
                            throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.DECLARED)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Class<?> getDeclaringClass()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1246]getDeclaringClass V. getEnclosingClass
By howard { dot } lovatt { at } iee { dot } org on 2005/01/06 17:20:28  Rate
The subtilty with this method is that anonymous inner classes are not counted as member of a class in the Java Language Specification whereas named inner classes are. Therefore this method returns null for an anonymous class. The alternative method getEnclosingClass works for both anonymous and named classes.

public Class<?> getEnclosingClass()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1247]_
By howard { dot } lovatt { at } iee { dot } org on 2005/01/06 17:22:23  Rate
The difference between this method and getDeclaringClass is explained under getDeclaringClass.

public Constructor<?> getEnclosingConstructor()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Method getEnclosingMethod()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public T[] getEnumConstants()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Field getField(String name)
               throws NoSuchFieldException,
                      SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC), NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[140]Class getField
By natali { dot } roiz { at } nsi { dot } co { dot } il on 2003/01/06 04:08:37  Rate
CallEventRecordManipulator.class.getField ( outputObj )  = 
                 ( Class.forName ( OutputTypeName )  ) data.get ( "OutputRec" ) ; 
 


public Field[] getFields()
                  throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Type[] getGenericInterfaces()
See Also:
TypeNotPresentException, ParameterizedType
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Type getGenericSuperclass()
See Also:
TypeNotPresentException, ParameterizedType
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Class[] getInterfaces()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Method getMethod(String name,
                        Class... parameterTypes)
                 throws NoSuchMethodException,
                        SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC), NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1521]Passing correct parameter data type
By Mikko Ohtamaa on 2005/08/23 06:42:30  Rate
// For primitive parameters, use primitive.class type, 
             // no Integer.class for example 
                                         
  
  
             Class [  ]  parameters; 
              
             if ( value instanceof Boolean )   {  
                 parameters = new Class [  ]   {  boolean.class  } ; 
              }  else  {  
                 parameters = new Class [  ]   {  value.getClass (  )   } ; 
              }   
              
             m = dataSource.getClass (  ) .getMethod ( methodName, parameters  ) ;


[1938]Example for use invoke method and getMethod
By kaman on 2007/11/01 05:27:55  Rate
public class MainClass {  
   public static void main ( String [  ]  args ) throws Exception  {  
     Method method = Text.class.getMethod ( "sayHello", null ) ; 
     method.invoke ( new Text (  )  ) ; 
    }  
  }  
  
  
 class Text {  
   public void sayHello (  )  {  
     System.out.println ( "Hello World" ) ; 
    }  
  } 


public Method getMethod(String name,
                        Class[] parameterTypes)
                 throws NoSuchMethodException,
                        SecurityException
See Also:
SecurityManager.checkPackageAccess(String), SecurityManager.checkMemberAccess(Class, int)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Method[] getMethods()
                    throws SecurityException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public int getModifiers()
See Also:
Modifier
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String getName()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Package getPackage()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public ProtectionDomain getProtectionDomain()
See Also:
RuntimePermission, SecurityManager.checkPermission(java.security.Permission), SecurityException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public URL getResource(String name)
See Also:
ClassLoader.getSystemResource(java.lang.String)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1413]Determine the names of the files in a directory associated with a class
By Anonymous on 2005/05/04 18:50:17  Rate
//determine the names of the files in a directory  
 //associated with a class. 
    
 String directory = ....; 
 URL url = MyClass.class.getResource ( directory ) ; 
 File file = new File ( new URI ( url.toString (  )  )  ) ; 
 String [  ]  list = file.list (  ) ;


public InputStream getResourceAsStream(String name)
See Also:
NullPointerException, ClassLoader.getSystemResourceAsStream(java.lang.String)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[963]Two ways to opening a file from the class path
By Anonymous on 2004/10/01 14:37:20  Rate
Both Class and Classloader have a method getResourceAsStream ( String )  for opening a file from the class path.

public Object[] getSigners()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String getSimpleName()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public Class<? super T> getSuperclass()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public TypeVariable<Class<T>>[] getTypeParameters()
See Also:
GenericDeclaration
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isAnnotation()
See Also:
isInterface()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
See Also:
AnnotatedElement
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isAnonymousClass()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isArray()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1896]possible alternative
By John Newman on 2007/06/29 14:24:01  Rate
this method is kind of slow, 
  
  
 object.getClass (  ) .getName (  ) .charAt ( 0 )  == ' [ ' 
  
  
 may work just as well. Can anyone think of any cases it would miss or return a false positive? 
  
  
 It is much faster!! I am not sure what isArray (  )  really does  ( native ) , but it is slow & this is orders of magnitude faster. So far I think it works fine.


public boolean isAssignableFrom(Class<?> cls)
See Also:
NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isEnum()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isInstance(Object obj)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isInterface()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isLocalClass()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isMemberClass()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isPrimitive()
See Also:
Void.TYPE, Double.TYPE, Float.TYPE, Long.TYPE, Integer.TYPE, Short.TYPE, Byte.TYPE, Character.TYPE, Boolean.TYPE
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public boolean isSynthetic()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public T newInstance()
              throws InstantiationException,
                     IllegalAccessException
See Also:
s.checkPackageAccess(), s.checkMemberAccess(this, Member.PUBLIC), SecurityException, ExceptionInInitializerError, InvocationTargetException, Constructor.newInstance
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public String toString()
See Also:
Object
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  

Popular Tags