简体   繁体   中英

Dynamically loading class in Java Android

Looking for the best way that I can define a class without knowing its name at the time of compilation. In PHP, this is done as follows:

$className = 'testclass';
$myClass = new $className();

In contrast, already in Java so do not be. I know it's ClassLoader, but I'm not sure if Android does so the same thing. I would ask for a specific code or even tips on how I can do it.

Regards.

What you are looking for is called Reflection in Java: http://developer.android.com/reference/java/lang/reflect/package-summary.html

Please note it is not possible to list classes in a certain package using reflection though.

You can load an existing class via Class.forName ; your class could also have a static initializer static { /* your init code */ } so that it could be run while loading the class.

Note also that all JDBC drivers are commonly loaded in this way.

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