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)
IE:
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?
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
You do it right now.
We call it --> Recursivity (if you call the same function from the function you call) Or simply.. a redirection.. You learn little by little what is the POTENTIAL of the programming :D
Welcome to StackOverflow :D Good Luck!
because if you call a class from another class, you need to create an object before. (OOP) Example:
Class X{ public functionX(){}}
Class Y {
X object = new X(); //Create an object to access to the function X
public functionY(){
object.functionX(); //you call the function from Class X
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.