将getClass()作为参数传递给另一个类

时间:2016-05-12 06:17:47

标签: java

1)我有一个名为Utilites的类,它执行一些字符串检查以确保“ID”符合标准。

2)我想将调用类的详细信息传递给Utilities类,以确定该类型的“ID”是否正确(MembersHolding之间)。

3)PremiumMemberMember的扩展类,并将所有参数传递给Member

4)目前,创建新的PremiumMemberjava.lang.Class而不是预期的library.Member

包含测试代码的主要方法的类

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**
    }

包含构造函数的类

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;   
}

用于检查ID号有效性的实用程序类

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";
    }

我不明白为什么实例化并假设自定义构造函数返回Java.lang.Class类?

谢谢!

1 个答案:

答案 0 :(得分:4)

您在[{1}}上致电getClass() - 这样就可以给您java.lang.reflect.Type ...实际上,您已拨打{{} {1}},你不想这样做。

我怀疑您想要更改Class.class方法以接受this.getClass().getClass()而不是validateId,然后只使用Class<?>等。(我还没有&#39;}检查了你如何使用课程的逻辑 - 让我们专注于开始使用正确的课程。)