0

I have many types of activity's, but if at a certain point activity is a TaskComplianceActivity then I want to handle it in a special way.

I could do:

if (activity.getClass().getName() == "au.net.example.myapp.TaskComplianceActivity")

But that is very ugly.

I have tried this, but it didn't work:

if (activity instanceof TaskComplianceActivity)

Does anyone have any suggestions on how I can cleanly do this?

5
  • 3
    Second way is right what problem u are getting? Commented Jan 12, 2016 at 8:11
  • The first way wouldn´t work, since you don´t compare strings that way. The second way with instanecof would also include a null check Commented Jan 12, 2016 at 8:12
  • If I step through the code I see: Incompatible conditional operand types Activity and TaskComplianceActivity TaskComplianceActivity cannot be resolved to a type Commented Jan 12, 2016 at 8:15
  • Testing the instance is in most cases bad smelling code. If it is possible to do the special handling right in TaskComplianceActivity this would be the prefered solution - just a thought... Commented Jan 12, 2016 at 8:16
  • "Incompatible conditional operand types" sounds like a compile error, so how can you "step through the code" if the code doesn't compile? Commented Jan 12, 2016 at 8:39

1 Answer 1

4

Try this:

if (activity.getClass().getName().equals(TaskComplianceActivity.class.getName()))

or this:

if (activity.getClass().getSimpleName().equals(TaskComplianceActivity.class.getSimpleName()))
Sign up to request clarification or add additional context in comments.

2 Comments

i didnt downvote, but obviously because you dont compare strings that way.
I get the error "TaskComplianceActivity cannot be resolved to a type" when I try your second one with getSimpleName(). It definitely exists though! What am I doing wrong?

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.