0

I want to add more support on my Java program, and don't know how to. Google didn't helped me on this one, so I'll ask it here. I want my Java program to see classes in a "mod" folder and then interact with them. For example, I have red and a green entities with certain code associated to it. They spawn randomly on a map. If somebody puts a blue entity in the mod folder, I want it to spawn too.

piet.t
  • 11,718
  • 21
  • 43
  • 52
Telno
  • 53
  • 2
  • 9
  • The google search term you need to use is "classpath". Here is one link: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html . Then look at the documentation for the class `java.lang.Class` to see how to load classes by name (you probably want a list of extensions to load in some text file, or use file system API to look for .class files) –  Jan 25 '19 at 20:40

2 Answers2

1

You just need to put the "mod" folder in the classpath and then find classes using java reflect API.

To make it simpler, all the classes will need to have something in common. For example, implement an interface or be defined in a particular package. You can use this library : https://github.com/ronmamo/reflections

For example:

Reflections reflections = new Reflections("mod");    
Set<Class<? extends ModInterface>> classes = reflections.getSubTypesOf(ModInterface.class);
jaudo
  • 2,022
  • 4
  • 28
  • 48
0

Assuming: all extension files present at program start

  • add extension folder to classpath
  • define an Extension interface (with whatever functions you want an extension to have)
  • make all extension classes implement Extension
  • expose a [Someclass].register(Extension e) static method in the main code
  • in each extension class call the registration in its static initializer
  • do whatever you want with all the extensions that have registered...

Assuming: dynamically loading extensions at runtime