1

Below is the sample java code

class Candy {
    static {
        print("Loading candy");
    }
}

class Gum {
    static { 
        print("Loading Gum"); 
    }
}

class Cookie {
    static { 
        print("Loading Cookie"); 
    }
}


public class SweetShop {
    public static void main(String[] args) {
        print("inside main");
        new Candy();
        print("after creating candy");
        try{
            Class.forName("Gum");   
        }
        catch(ClassNotFoundException e) {
            print("could not find gum class");
        }
        print("After Class.forName(\"Gum\")");
        new Cookie();
        print("After creating Cookie");
    }
}

When execute always i am getting out put as

inside main

Loading candy

after creating candy

could not find gum class

After Class.forName("Gum")

Loading Cookie Please provide some help. After creating Cookie

Community
  • 1
  • 1
user1891916
  • 951
  • 1
  • 8
  • 9

2 Answers2

0

I think you class is package private as you have not specified any access modifier to it.

Try:

public class Gum {
   static { print("Loading Gum"); }
}
cs95
  • 379,657
  • 97
  • 704
  • 746
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • If that is the solution, would the answer to this question also not work? http://stackoverflow.com/questions/4202252/how-does-class-forname-work – CubeJockey Apr 17 '15 at 18:33
  • 1
    @Trobbins if they are in the same package then it will work hence I have asked for the package structure to get more clarity. – StackFlowed Apr 17 '15 at 18:34
  • Right, but his code snippet implies the code is within the same file, which is why I asked. Guess I'm just making an Ass out of U and Me :) – CubeJockey Apr 17 '15 at 19:02
0

Try this if you have a package:

   Class.forName("package_name.Gum");
Slow Trout
  • 492
  • 3
  • 13