Return Name of class from instance of that class

I need a quick approach to something like:

  MyClass mc = new MyClass();
  String theName = ClassNameProvider.getName(mc); // returns 'MyClass'


I think your requirement falls in the gap for apex but we have the ability to do one of following things:

We can retrieve the name of an object using code such as

String name = MyClass.class.getName(); //returns MyClass

We can check whether the instance of a particular type using

Boolean isSame = mc instanceof MyClass; //returns true

Or if we want to get the name from an instance of an unknown type we can do:

String name = String.valueOf(mc).split(':')[0];//returns MyClass

Hopefully one of those covers your need. See the discussion to a similar question here for more info.

Source : Link , Question Author : max , Answer Author : Community

Leave a Comment