There
are two ways to load class.
a.
Implicit class loading
Implicit
class loading occurs when a class is loaded as result of a reference,
instantiation, or inheritance.
b.
Explicit class loading
Explicit
class loading occurs when a class is loaded by using 'loadClass()'
method of ClassLoader class or using 'forName()' of class
java.lang.Class. If the class is already loaded, then a reference is
simply returned
b.1
Load Class using loadClass()
public class Employee { int id; String firstName, lastName; Employee(int id, String firstName, String lastName){ this.id = id; this.firstName = firstName; this.lastName = lastName; } }
public class LoadClass { public static void main(String args[]) throws ClassNotFoundException{ ClassLoader cl = ClassLoader.getSystemClassLoader(); Class myClass = cl.loadClass("Employee"); System.out.println(myClass.getName()); } }
Output
Employee
b.2
Load Class using forName ()
public class LoadClass { public static void main(String args[]) throws ClassNotFoundException{ Class myClass = Class.forName("Employee"); System.out.println(myClass.getName()); } }
Output
Employee
No comments:
Post a Comment