lundi 28 mai 2018

Java Reflection: Call abstract interface methods without instantiation

I am currently facing problems integrating the existing Piketec TPT Java API (http://javadoc.jenkins.io/plugin/piketec-tpt/com/piketec/tpt/api/package-summary.html) in a Java project by using Reflection.

The TPT Api provides an interface called "TptApi", which contains several abstract methods, that are used to access TPT projects.

I have already integrated other APIs such as the Dox4j-API, where a class instance was used as invokation target. Obvisouly, this is not the correct way for accessing method from an interface.

My goal is to access the method "OpenResult openProject(File f)" from the TptApi interface (http://javadoc.jenkins.io/plugin/piketec-tpt/com/piketec/tpt/api/TptApi.html#openProject-java.io.File-).

My code:

ClassLoader cl = new URLClassLoader(...); Map c = new HashMap();

File file = new File("test.prj");

c.put("TptApi", cl.loadClass("com.piketec.tpt.api.TptApi")); c.put("OpenResult", cl.loadClass("com.piketec.tpt.api.OpenResult"));

//The way I did it with 'normal' classes, not applicable with the interface: //Object target = ((Class) c.get("TptApi")).newInstance();

OpenResult or = (OpenResult)((Class) c.get("TptApi")).getMethod("openProject", new Class[]{File.class}).invoke(target, new Object[]{_file});

So how do I access abstract interface methods by Reflection?





Aucun commentaire:

Enregistrer un commentaire