khaleel. Powered by Blogger.

class.forName()

Monday 6 June 2011

Class.forName():

Class.forName() is used to load the class on to the JVM without creating the object.
    We do this because to execute if any static blocks are available.

Ex:
    public class Test{
      static{
          System.out.prinln("we are in static block of test class");
        }
    public void display(){
          System.out.prinln("we are in display method");
    }
      }
   
    public class MyApp{
    p.s.v.main(String args[]){
    try{
        Class c=Class.forName("Test");
        System.out.prinln(c.getName());
        System.out.prinln(c.getPackage());
        Object o=c.newInstace();
        Test t=(Test)o;
        t.display();
       }
    }
  When we execute the above program Test class will be loaded into JVM without creating object of Test class.Thenafter JVM executes static block of Test class and it creates Class object and place information about class and name of package and location of Test(loaded class)class.
  To get the name of the class and package we use getName and getPackage methods.
  To create the object of a class we have to use newInstance method.That object is stored as super class Object.So we have to typecast from superclass object to our class(Test).

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Promote Your Blog

About This Blog

This blog is for java lovers

Total Pageviews

About Me

khaleel-bapatla
BAPATLA, ap, India
simple and honest
View my complete profile

  © Blogger template On The Road by Ourblogtemplates.com 2009

Back to TOP