0

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.

6
  • 1
    Why would you do such a thing? Commented Mar 4, 2014 at 14:18
  • Define a class or load an existing class? Commented Mar 4, 2014 at 14:19
  • @MarioStoilov I thought of a simple plugin system, which would be just loaded when the application starts. However, the plugin can dynamically add, so I do not know their names. Commented Mar 4, 2014 at 14:22
  • If you are looking for loading an existing class, use Class.forName(classname) Commented Mar 4, 2014 at 14:24
  • @robermann your reply is very helpful for me, thanks. Commented Mar 4, 2014 at 14:37

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.