If I have an Activity class called TestActivity in my application, is there a way to get its class by its name like in this example:
Class<?> c = getClassByName("TestActivity");
The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.
A method must be created in the class with the name of the method, followed by parentheses (). The method definition consists of a method header and method body. We can call a method by using the following: method_name(); //non static method calling.
Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.
forName(String name, boolean initialize, ClassLoader loader) method returns the Class object associated with the class or interface with the given string name, using the given class loader. The specified class loader is used to load the class or interface.
use forName instead..
something like this..
try { Class<?> act = Class.forName("com.bla.TestActivity"); } catch (ClassNotFoundException e) { e.printStackTrace(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With