简体   繁体   中英

How to declare an object created by a class loaded by classloader

I have to use a classloader to load a class from a custom jar file, and the following works:

Class<?> JasperPrint = urlClassLoader.loadClass("net.sf.jasperreports.engine.JasperPrint");

How to I declare an object I create with the constructor? Below, Eclipse complains that JasperPrint is not an object:

JasperPrint jp = JasperPrint.getConstructor().newInstance();

Also just to declare an object without instantiating, since the following also does not work:

JasperPrint jp;

Your JasperPrint is not a class. It is a variable holding the loaded Class definition net.sf.jasperreports.engine.JasperPrint. On a Class instance you can call newInstance() to create a new instance using the no-arg constructor:

Class<?> jasperPrintClazz = urlClassLoader.loadClass("net.sf.jasperreports.engine.JasperPrint");
Object jasperPrint = jasperPrintClazz.newInstance();

Variable jasperPrint is an instance (object) of type JasperPrint.

If you are loading a class dynamically you do not know it's static type (at compilation type). You can either cast it to a JasperPrint 's interface if you have it on your classpath when compiling your code. Otherwise you will need to use reflection to call the newly created object's methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM