May 2, 2013

Get class name of a object using Java

To get class name of a object, call its getClass().getName().

Example:

Get class name of a object
Get class name of a object


package com.example.androidclassname;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 TextView info;
 ImageView image;
 LinearLayout screen;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  screen = (LinearLayout)findViewById(R.id.screen);
  info = (TextView)findViewById(R.id.info);
  image = (ImageView)findViewById(R.id.image);
  
  screen.setOnClickListener(onClickListener);
  info.setOnClickListener(onClickListener);
  image.setOnClickListener(onClickListener);
 }

 OnClickListener onClickListener = 
   new OnClickListener(){

    @Override
    public void onClick(View v) {
     
     String className = v.getClass().getName();
     String simpleName = v.getClass().getSimpleName();
     String canonicalName = v.getClass().getCanonicalName();
     
     if(canonicalName == null){
      canonicalName = "null";
     }
     
     String s = "Name: " + className + "\n"
       + "SimpleName: " + simpleName + "\n"
       + "CanonicalName: " + canonicalName + "\n";
     info.setText(s);
    }
  
 };

}


No comments:

Post a Comment

Infolinks In Text Ads