簡體   English   中英

Java:在這種情況下如何解析字符串?

[英]Java: how to parse a string in this situation?

所以我在Java中創建了一個簡單的類,如下所示:

public class Book {
    private String author;
    private String title;

    public Book (String author, String title) {
        this.author = author;
        this.title = title;
    }
}

public void checkInfo     

有沒有一種方法可以解析字符串(屬性)以獲取像這樣的Book屬性,而不是執行bookA.title

Book bookA = new Book("George Orwell","Animal Farm")

String property = "title";
System.out.print(bookA.property);

預先感謝!

如果您確實想以String訪問許多屬性,建議您使用Map<String, String>這樣:

public class Book
{
    private Map<String, String> properties = new HashMap();

    public void setProperty(String name, String value)
    {
        properties.set(name,string);
    }

    public String getProperty(String name)
    {
        return properties.get(name);
    }
}

現在您可以像這樣使用:

Book book = new Book();

book.setProperty("title","Animal Farm");
book.setProperty("author","George Orwell");

System.out.println("Book: " + book.getProperty("title") + " by " + book.getProperty("author"))

您已將Book創建為一個對象。
因此,將其視為對象並添加getter和setter。

在這種情況下,這將是方法getTitle()和單獨的方法getAuthor()
有關getter和setter的更多信息,請參見對此之前StackOverflow帖子的回復

您可以使用反射:

 Field f = bookA.getClass().getDeclaredField("title");
 f.setAccessible(true);
 String title = (String) f.get(bookA);
 System.out.println(title);

首先,因為title是私有的,所以您的代碼將無法工作。 其次,我不知道為什么將Book類設置為靜態。 最后,此(Java)是面向對象的編程,因此應將其視為對象。

創建課程時,您還需要添加Getters和Setters來訪問其中的信息。 代碼如下所示:

public class Book {
    private String author;
    private String title;

    public Book (String author, String title) {
        this.author = author;
        this.title = title;
    }
}

public String getTitle(){
    return this.title;
}

public String getAuthor(){
    return this.author;
}

訪問數據

Book bookA = new Book("George Orwell","Animal Farm")

System.out.print("Book: " + bookA.getTitle() + " by " + bookA.getAuthor());

這將返回:

Book: Animal Farm by George Orwell

如果您從代碼中看到以下幾行:

private String author;  // both are private variables
private String title;  

這里authortitle都是private String。 因此,您不能在類外部訪問這些屬性。

因此,您需要添加可用於訪問屬性的公共getterssetters

你應該改變你的對象類..添加getter和setter方法..這是例子:

public class Book{ 
  String myauthor;
  String mytitle;
public Book (String author, String title){
  myauthor=author;
  mytitle=title;
}
public void setAuthor(String Autor){
myauthor=author;
}
public String getAuthor(){
return myauthor;
}
}

並為“標題”創建設置器和獲取器..如果您想獲得標題/作者,只需調用

Book.getAuthor();

如果您不想在類中使用getter / setter方法,則可以將訪問修飾符定義為受static關鍵字保護的示例,例如:在com.test包下-有兩個類,一個是Book類,另一個是BookInSamePackage在Book類中;如果您將屬性標題定義為受保護的靜態String標題,則在BookInSamePackage類中;您可以這樣訪問:'Book.title'。如果要在另一個包的類中使用此title屬性,則該類需要擴展Book類並可以這樣訪問:另一個包的子類中的Book.title。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM