Why can't I check if my class implements its own interface in a web application?

I am trying to write something like a frame. I need to find a specific folder on my computer and be able to get all the class files that exist that implement my interface. Although I know how to scan a folder and check all class files, somehow I can’t check if the reading class implements my interface.

if (Game.class.isAssignableFrom(classInFolder)) { //Do sth here } 

The approach I tried but it never jumps in if clause - Game is my Interface

 public interface Game { public void startAlgorithm(); } 

and classInFolder is the class I got from my folder. It's funny if I try to do the same with some library interface - let them say that Serializable works fine - I tried. What else when I wrote something like this

 Type[] type = classInFolder.getGenericInterfaces(); for (int i = 0;i<type.length;++i) { System.out.println("interface = " + type[i]); if (type[i] instanceof Game){ System.out.println("It is"); } } 

I got my console output - interface = mypackage.Game But there wasn’t "This." The same thing happened with my own annotation in the class that I tried to use - I can’t check if my class implements my interfaces, but it works when these are interfaces from some library. I am deploying my project on tomcat v 7.0, everything works on Java 7 on Eclipse using Spring.

I would be grateful for any ideas on what might happen.

+4
source share
4 answers

Your Game class is probably loaded by the tomcat class loader.

Your classInFolder is probably loaded by your own custom class loader.

You need to make sure that the first bootloader is the parent of the second bootloader

 ClassLoader parent = Game.class.getClassLoader(); new MyClassLoader(parent, ...) 
+1
source

I suspect you are loading your classes with different ClassLoader s. A class loaded by one class loader does not match the same class that is loaded using another class loader.

Try downloading it with the same ClassLoader .


 Object a1 = new ClassLoader() {}.loadClass("A"); Object a2 = new ClassLoader() {}.loadClass("A"); return a1.getClass().equals(a2.getClass()); 

will return false .

+2
source

In your example, "This" is not output, because you must use the instance of the desired class to the left of the operatorof instance, while you are using the Type instance there.

Try using Class.getInterfaces () to get the interfaces implemented by the class and look at your interface in the array returned by getInterfaces ().

+2
source

Using the instanceof operator , you test an instance of an object, not an interface.

To check the interface, try to get the interfaces, since there can be more than one, rename the list and map the type as shown below:

  for (Class ifce : type[i].getClass().getInterfaces()) { if (ifce.equals(Game.class)) { System.out.println("It is"); } } 
+2
source

Source: https://habr.com/ru/post/1445552/


All Articles