繁体   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