Search code examples
javaclassloader

Java Call class function from loaded class


How would I, if possible, call a function in my Main class in the class that I load? (I know that is impossible to understand, so I'll explain)

I.E:

public class SomeClass
{
     public SomeClass
     {
          //load a class here
     }

     public void FuncToCall() {}
}

//In a separate file, dynamically loaded.
public class LoadedClass
{
     public LoadedClass
     {
          //Call a function in the class that loads this
          SomeClass.FuncToCall();
     }
}

So I would end up having 2 files: SomeClass.class and LoadedClass.class. I guess my main question is, how do I reference SomeClass in LoadedClass?

**EDIT:

So maybe I should better explain the use case. A java program dynamically loads the "SomeClass" script from a folder. The script then downloads a .jar file from the internet and opens and runs the "LoadedClass" script within that. How do I use functions in SomeClass in LoadedClass if SomeClass isn't in the same .jar or in a .jar at all?


Solution

  • You just do it..

    If they are in different packages you have to either import the class or use the fully qualified name.

    Let me see if I get it.

    Check this running sample with modifications to your source code:

    C:\Users\oreyes\java>type SomeClass.java LoadedClass.java Main.java
    //SomeClass.java
    public class SomeClass{
         public SomeClass () /* added () */ {
              //load a class here
              LoadedClass lc = new LoadedClass( this );
         }
         public  void funcToCall() {
             System.out.println("SomeClass.functToCall: Being invoked :)");
         }
    }
    //LoadedClass.java
    //In a separate file, dynamically loaded.
    public class LoadedClass {
         public LoadedClass( SomeClass sc )/*added () */ {
              //Call a function in the class that loads this
              //SomeClass.funcToCall();
              sc.funcToCall();
         }
    }
    //Main.java
    //
    public class Main {
        public static void main( String ... args ) {
            new SomeClass();
        }
    }
    C:\Users\oreyes\java>javac SomeClass.java LoadedClass.java Main.java
    C:\Users\oreyes\java>java Main
    SomeClass.functToCall: Being invoked :)
    C:\Users\oreyes\java>
    

    What a did was to pass a reference of the loader class into the loaded, and from there...just invoke the method.

    I hope this helps.

    EDIT

    As per your comment it looks like what you need is to use Reflection