0

I'm playing with reflection on Android. I've saved JAR file on device and I'm trying to get class from this JAR but it isn't working and I'm getting exception:

java.lang.ClassNotFoundException: Main.class

My code:

File classFile = new File(getExternalFilesDir(null) + File.separator);
URLClassLoader classLoader = new URLClassLoader(new URL[] { classFile.toURI().toURL() });
Class classToInvestigate = classLoader.loadClass("Main.class");

Also I tried saved there Main.class file, but I'm still getting errors. Is there something I'm missing? Thank you.

VladoS24
  • 47
  • 8

1 Answers1

0

The way you load a class is as follow:

Class<?> stringBuilder = ClassLoader.getSystemClassLoader().loadClass("java.lang.StringBuilder");

Another approach:

Class.forName("java.lang.StringBuilder");

UPDATED: Take a look at https://stackoverflow.com/a/6860579/1715121

Take a look at the FQCN of Main class.

Ele
  • 33,468
  • 7
  • 37
  • 75
  • Still not working. I have HelloWorld.jar only with package com.helloworld and class Main. I've changed code to `.loadClass("com.helloworld.Main");` but same error. – VladoS24 Dec 03 '17 at 01:27
  • Answer updated: `Class.forName("java.lang.StringBuilder");` – Ele Dec 03 '17 at 01:29
  • But this JAR is saved on device and I need to get this JAR first with his location and then somehow look for name, am I wrong? – VladoS24 Dec 03 '17 at 01:33
  • Every class will be loaded on demand for the class loader, regardless of its location. When you're calling the method `forName` or method `loadClass` that class will be loaded at runtime. – Ele Dec 03 '17 at 01:37
  • 1
    Yes, but first of all, I run application, download JAR from URL, save into device and then try to load that class. But also tried and I've this error now: `Didn't find class "com.helloworld.Main" on path: DexPathList[[zip file "/data/app/testapp/s-1/base.apk"` – VladoS24 Dec 03 '17 at 01:41
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160361/discussion-between-vlados24-and-eleazar-enrique). – VladoS24 Dec 03 '17 at 02:12