Passing getClass() as a parameter to a different class

1) I have a class called Utilites that performs some string checks to make sure an "ID" conforms to a standard.

2) I wanted to pass the details of the calling class to the Utilities class to decide if the "ID" is correct for that type (between Members and Holding).

3) PremiumMember is an extended class of Member and passes all parameters to Member

4) At the moment, creating a new PremiumMember has the Class java.lang.Class instead of the expected library.Member

The class containing the main method to test the code

package library;
import lib.Utilities;
public class LibraryManagementSystem 
{
    static Member[] members = new Member[15];

    public static void main(String[] args) 
    {
        members[0] = new PremiumMember("p000001", "Mr Bill Wrong"); // Prints **Java.lang.Class**
        System.out.println(members[0].getClass());                  // Prints **library.Member**
    }

The class containing the constructor

import lib.Utilities;
public abstract class Member {

public Member(String memberID, String fullName)     // Constructor for each member
{
    memberNumber = Utilities.validateId(memberID, this.getClass()); // Makes sure that the ID conforms to all requirements
    this.fullName = fullName;   
}

The utilities class which checks for validity of an ID number

import library.Holding;
import library.Member;
public class Utilities {

public static String validateId(String checkId, Type classType)
{   
    if (classType.getClass().getGenericSuperclass() == Holding.class)
    {
        // Deal with code one way
        return "Is of Holding Class"
    }
    else if (classType.getClass().getGenericSuperclass() == Member.class)
    {
        // Deal with code another way
        return "Is of Member Class"
    }
    else
    {
        System.out.println(classType.getClass() + " Not of  Member/Holding class");
        return "INVALID";
    }

I don't understand why instantiating and supposedly going though a custom constructor returns the Java.lang.Class class?

Thanks!

Jon Skeet
people
quotationmark

You're calling getClass() on a java.lang.reflect.Type - so that's just going to give you Class.class... Effectively, you've called this.getClass().getClass(), and you don't want to do that.

I suspect you want to change your validateId method to accept a Class<?> instead of a Type, and then just use classType.getGenericSuperclass() etc. (I haven't checked your logic over how you're using the class - let's focus on getting the right class to start with.)

people

See more on this question at Stackoverflow