1)我有一個名爲Utilites
的類,它執行一些字符串檢查以確保「ID」符合標準。將getClass()作爲參數傳遞給不同的類
2)我想將調用類的詳細信息傳遞給Utilities
類,以確定該類型的「ID」是否正確(在Members
和Holding
之間)。
3)PremiumMember
是擴展類的Member
和傳遞所有參數,以Member
4)目前,創建一個新的PremiumMember
已經類java.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
類的有效性?
謝謝!
能否請你解釋一下'你在java.lang.reflect.Type上調用getClass()'部分@ – Abhishek
@Abhishek:看看'validateId'中的代碼, - 類型參數的類型是類型,方法的主體使用'classType.getClass()'... –
這是一個清晰而簡潔的迴應,謝謝。 我已將發送給'Utilities.ValidateId'的參數更改爲'this.getClass()',並且已將接受的參數更改爲'class > classType'。 'ValidateId'方法中的'sysout'成功顯示'library.Member'! – Ari