Jump to content

[1.12.2] Can't manage to dynamically load classes from package


frxtn

Recommended Posts

Heya,

 

I am working on a utility mod for minecraft. So far I have loaded the mod classes through plain instantiation in the manager constructor.

 

I decided that I wanted to load classes dynamically from the mod package so that i don't have to manually instantiate them (and remove them when i decide i dont want to use them).

 

So far I tried literally a dozen methods i found on stackoverflow or in this forum, but none would find any class in my class package although it definitely contains them.

 

A selection of methods i tried using:

 

I am somewhat new to java,having a background in c++/c#.

 

I am really desperately looking for a solution.

I am trying to load all classes from my package "com.mymod.mods.*" (i tried using the package name with and without the .*).

 

I tried implementing the methods in the preInit and also in the init.

 

I am losing my mind over this and i can't bring myself to continue working on the actual mod until i resolved this issue and believe me, i spent hours over hours trying to fix this on my own through googling and trying. Right now i really feel like i am missing a vital bit of understanding that's keeping me from progressing in this issue.

 

I am aware that the information i'm presenting might be lacking, I just can't put my finger on what exactly i should provide in terms of information. I am gladly providing you any info you need if you could specify what you need to know in order to help me (or in order to understand my issue better!)

 

I would really appreciate any help you guys can give me!! 

Edited by frxtn
added specification
Link to comment
Share on other sites

38 minutes ago, diesieben07 said:

Why do you want to do this? Classpath scanning is usually considered an antipattern...

 

For convenience sake, right now the number of module classes is still overviewable yet with time i plan on adding a great amount of modules. If i have 100 modules i really don't want to manually instaniate every single one of them. upon removing one i'd have to manually remove the instantiation too. 

 

i can imagine that classpath scanning can result in problems, yet i really want to implement this. i might ofc, like you said, find out that it is causing me more problems than good, and i will gladly accept it but i want to at least get it to work so I can personally make the experience. Who knows, even if it is not directly useful, i might at least learn something new.

 

so if you (from the little info i could provide rn) could give me a starting step (or tell me to write up a sample implementation the way i tried it before so you can better see what my mistake is) I would really appreciate it.

 

regards

Edited by frxtn
Link to comment
Share on other sites

8 hours ago, diesieben07 said:

Sounds like a job for ServiceLoader.

After reading through this I must say I haven't gotten anything from it that really helps me continue. 

My problem actually lies way before the class loading itself, my code can't seem to locate the classes in the first place, although i'm giving the right package.

I will include sample code which I used and how I failed so far:

 

    public static Collection<Class<?>> find(String path) {
        String scannedPath = path.replace(PKG_SEPARATOR, DIR_SEPARATOR);
        URL scannedUrl = Thread.currentThread().getContextClassLoader().getResource(scannedPath);
        if (scannedUrl == null) {
            throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR, scannedPath, path));
        }
        File scannedDir = new File(scannedUrl.getFile());
        List<Class<?>> classes = new ArrayList<Class<?>>();
        for (File file : scannedDir.listFiles()) {
        	Logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!MODULE FOUND!!!!!!!!!!!!!!!!!!!!!!!!"); //this was just to debug if a class was found
            classes.addAll(find(file, path));
        }
        return classes;
    }

	private static List<Class<?>> find(File file, String scannedPackage) {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        String resource = scannedPackage + PKG_SEPARATOR + file.getName();
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                classes.addAll(find(child, resource));
            }
        } else if (resource.endsWith(CLASS_FILE_SUFFIX)) {
            int endIndex = resource.length() - CLASS_FILE_SUFFIX.length();
            String className = resource.substring(0, endIndex);
            try {
                classes.add(Class.forName(className));
            } catch (ClassNotFoundException ignore) {
            }
        }
        return classes;
    }

 

I put "com.mymod.modules" and "com.mymod.modules.*" as the package (which, as i checked,  is the package my module classes are in). It didn't find them.

 

Neither did this implementation: 

 

/**
	 * Private helper method
	 * 
	 * @param directory
	 *            The directory to start with
	 * @param pckgname
	 *            The package name to search for. Will be needed for getting the
	 *            Class object.
	 * @param classes
	 *            if a file isn't loaded but still is in the directory
	 * @throws ClassNotFoundException
	 */
	private static void checkDirectory(File directory, String pckgname,
	        ArrayList<Class<?>> classes) throws ClassNotFoundException {
	    File tmpDirectory;

	    if (directory.exists() && directory.isDirectory()) {
	        final String[] files = directory.list();

	        for (final String file : files) {
	            if (file.endsWith(".class")) {
	                try {
	                    classes.add(Class.forName(pckgname + '.'
	                            + file.substring(0, file.length() - 6)));
	                } catch (final NoClassDefFoundError e) {
	                    // do nothing. this class hasn't been found by the
	                    // loader, and we don't care.
	                }
	            } else if ((tmpDirectory = new File(directory, file))
	                    .isDirectory()) {
	                checkDirectory(tmpDirectory, pckgname + "." + file, classes);
	            }
	        }
	    }
	}

	/**
	 * Private helper method.
	 * 
	 * @param connection
	 *            the connection to the jar
	 * @param pckgname
	 *            the package name to search for
	 * @param classes
	 *            the current ArrayList of all classes. This method will simply
	 *            add new classes.
	 * @throws ClassNotFoundException
	 *             if a file isn't loaded but still is in the jar file
	 * @throws IOException
	 *             if it can't correctly read from the jar file.
	 */
	private static void checkJarFile(JarURLConnection connection,
	        String pckgname, ArrayList<Class<?>> classes)
	        throws ClassNotFoundException, IOException {
	    final JarFile jarFile = connection.getJarFile();
	    final Enumeration<JarEntry> entries = jarFile.entries();
	    String name;

	    for (JarEntry jarEntry = null; entries.hasMoreElements()
	            && ((jarEntry = entries.nextElement()) != null);) {
	        name = jarEntry.getName();

	        if (name.contains(".class")) {
	            name = name.substring(0, name.length() - 6).replace('/', '.');

	            if (name.contains(pckgname)) {
	                classes.add(Class.forName(name));
	            }
	        }
	    }
	}

	/**
	 * Attempts to list all the classes in the specified package as determined
	 * by the context class loader
	 * 
	 * @param pckgname
	 *            the package name to search
	 * @return a list of classes that exist within that package
	 * @throws ClassNotFoundException
	 *             if something went wrong
	 */
	public static ArrayList<Class<?>> getClassesForPackage(String pckgname)
	        throws ClassNotFoundException {
	    final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

	    try {
	        final ClassLoader cld = Thread.currentThread()
	                .getContextClassLoader();

	        if (cld == null)
	            throw new ClassNotFoundException("Can't get class loader.");

	        final Enumeration<URL> resources = cld.getResources(pckgname
	                .replace('.', '/'));
	        URLConnection connection;

	        for (URL url = null; resources.hasMoreElements()
	                && ((url = resources.nextElement()) != null);) {
	            try {
	                connection = url.openConnection();

	                if (connection instanceof JarURLConnection) {
	                    checkJarFile((JarURLConnection) connection, pckgname,
	                            classes);
	                } else {
	                    try {
	                        checkDirectory(
	                                new File(URLDecoder.decode(url.getPath(),
	                                        "UTF-8")), pckgname, classes);
	                    } catch (final UnsupportedEncodingException ex) {
	                        throw new ClassNotFoundException(
	                                pckgname
	                                        + " does not appear to be a valid package (Unsupported encoding)",
	                                ex);
	                    }
	                }
	            } catch (final IOException ioex) {
	                throw new ClassNotFoundException(
	                        "IOException was thrown when trying to get all resources for "
	                                + pckgname, ioex);
	            }
	        }
	    } catch (final NullPointerException ex) {
	        throw new ClassNotFoundException(
	                pckgname
	                        + " does not appear to be a valid package (Null pointer exception)",
	                ex);
	    } catch (final IOException ioex) {
	        throw new ClassNotFoundException(
	                "IOException was thrown when trying to get all resources for "
	                        + pckgname, ioex);
	    }

	    return classes;
	}

 

I also tried half a dozen other implementations of any form of package scanning. I have no idea why i cant find any classes.

 

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • So I saw that mixin is shipped as a library with forge, but is it available for 1.7.10 ?  
    • So I've read the EULA, and lets be straight...     If I split my modpack(of my mods, yeah I'm nuts) into several(many) individual mods(like just one boss) with minor additions(plus not working together), then have a complete/modpack version on patreon/onlyfans having each addon work together... Would people buy my idea?
    • German A1 – C1, TestDAF, Goethe B1, B2, C1, C2, valid GOETHE certificate German A1 – C1, TestDAF, Goethe B1, B2, C1, C2, valid GOETHE certificate(+27(838-80-8170
    • Done, it still crashed. New log https://paste.ee/p/kYv6e
    • I am migrating a mod from 1.16.5 to 1.20.2 The version for 1.16.5 can be found here https://github.com/beothorn/automataCraft For the block called automata_start, it uses TileEntities and has blockstates, model/block and textures on json files. This is currently working fine on 1.16.5 https://github.com/beothorn/automataCraft/tree/master/src/main/resources/assets/automata For 1.20.2 I migrated the logic from TileEntities to BlockEntity. The mod is working fine. All blocks and Items are working with the correct textures except for the textures for each state of the automata_start block. No changes where made to the json files. This is the branch I am working on (there were some refactorings, but all is basically the same): https://github.com/beothorn/automataCraft/tree/1_20/src/main/resources/assets/automata The only difference I can think that may be related is that i had to implement createBlockStateDefinition on the BaseEntityBlock: https://github.com/beothorn/automataCraft/blob/1_20/src/main/java/br/com/isageek/automata/automata/AutomataStartBlock.java#L43 This is driving me crazy. I know the jsons are being loaded as I put a breakpoint at `net.minecraft.client.resources.model.ModelBakery#loadModel` and I can see BlockModelDefinition.fromJsonElement being called with automata_start. I also printed the state from the arguments of the tick function call and they look correct (https://github.com/beothorn/automataCraft/blob/1_20/src/main/java/br/com/isageek/automata/automata/Ticker.java#L32 ): blockState Block{automata:automata_start}[state=loadreplaceables] In game, all I see is the no textures. I think it is weird it is not the "missing texture" texture so I think it may be related to the material, but I had no success tweaking it (https://github.com/beothorn/automataCraft/blob/1_20/src/main/java/br/com/isageek/automata/automata/AutomataStartBlock.java#L37).   public static final Property<AutomataStartState> state = EnumProperty.create("state", AutomataStartState.class); private final AtomicReference<RegistryObject<BlockEntityType<?>>> blockEntityType; private final Map<String, RegistryObject<Block>> registeredBlocks; public AutomataStartBlock( final AtomicReference<RegistryObject<BlockEntityType<?>>> blockEntityType, final Map<String, RegistryObject<Block>> registeredBlocks ) { super(BlockBehaviour.Properties.of().mapColor(MapColor.STONE).strength(1.5F, 6.0F)); this.blockEntityType = blockEntityType; this.registeredBlocks = registeredBlocks; this.registerDefaultState(this.getStateDefinition().any().setValue(state, AutomataStartState.LOAD_REPLACEABLES)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateBuilder) { stateBuilder.add(state); }     So my cry for help is, anyone has any ideas? Is there a way to easily debug this, for example somewhere where I can list the textures for a given state, or make sure this is loaded?   Thanks in advance for the hints
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.