Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting class by its name

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"); 
like image 900
Urho Avatar asked Apr 12 '12 08:04

Urho


People also ask

How can I get just a class name?

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.

How do you call a method by class name?

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.

Can we use class name in method?

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.

How do I find class Fornames?

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.


1 Answers

use forName instead..

something like this..

 try {     Class<?> act = Class.forName("com.bla.TestActivity");  } catch (ClassNotFoundException e) {         e.printStackTrace(); } 
like image 67
ngesh Avatar answered Sep 22 '22 15:09

ngesh