Q:

Convert enum within one class to another in Java

I have the following code in Java, trying to convert enum within one Class to another one:
class Test1 {

    UserType type;

    public enum UserType {
    PENDING,
    ACTIVE,
    INACTIVE,
    DELETED;
    }
}

class Test2 {

    UserType type;

    public enum UserType {
    PENDING,
    ACTIVE,
    INACTIVE,
    DELETED;
    }
}

public class TestClass {
    public static void main(String args[]) {
        Test1 test = new Test1();
        test.type = (Test2.UserType)Test1.UserType.PENDING;
    }
}

Then got the following info:
    /TestClass.java:29: error: incompatible types: Test1.UserType cannot be converted to Test2.UserType
            test.type = (Test2.UserType)Test1.UserType.PENDING;
How to cast the enum from one class to another class?

A:

Assuming you cannot refactor the code so both classes uses the same top-level enum, you can rely on the fact that the enum values all have the same name:
Test1 test1 = new Test1();
test1.type = Test1.UserType.PENDING;
Test2 test2 = new Test2();
test2.type = Test2.UserType.valueOf(test1.type.name());
System.out.println(test2.type); // prints: PENDING

Of course, you might need to check for null first:
test2.type = (test1.type == null ? null : Test2.UserType.valueOf(test1.type.name()));

