Search code examples
javaclassloader

Loading a class in Java


I would like to load a class that is located within another project; following the structure of my packages, projects etc.:

--ProjectA
  --package myPackageA
    --myClassA

 --ProjectB
  --package myPackageB
    --myClassB
      --myMethodB

Within myMethodB, I want to load the class "myClassA" from ProjectA. I know how to load the class if it were within ProjectB, but I don't know how to reference it with my current structure.

The only thing I have so far is following:

Class<?> c = thread.currentThread().getContextClassLoader().loadClass("location_of_myClassA");

In short: What do I write instead of "location_of_myClassA"?


Solution

  • If the classloader knows about both of them, you just need to give the fully-qualified class name:

    ...loadClass("myPackageA.myClassA")
    

    ClassLoader.loadClass doesn't need to be given a "location" - that's part of how it's initialized (e.g. to point to a particular jar file or set of jar files).