Java:在这种情况下如何解析字符串?

时间:2016-05-15 01:58:30

标签: java string class

所以我用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);

非常感谢!

7 个答案:

答案 0 :(得分:2)

如果您真的想以gem install nokogiri --pre的形式访问多个属性,建议您使用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);
    }
}

答案 1 :(得分:1)

您已将Book创建为对象 因此,将其视为对象并添加getter和setter。

在这种情况下,这将是一种方法getTitle()和一种单独的方法getAuthor() 有关getter和setter的更多信息,请参阅对this previous StackOverflow post

的回复

答案 2 :(得分:1)

您可以使用反射:

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

答案 3 :(得分:1)

首先,您的代码无效,因为title是私有的。其次,我不知道为什么你将Book类设置为静态。最后,这个(Java)是面向对象的编程,因此将其视为一个对象。

创建课程时,您还可以添加Getters&amp; 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

答案 4 :(得分:0)

如果您看到代码中的这几行:

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

此处authortitle都是private字符串。所以你不能在课外访问这些属性。

因此,您需要添加可用于访问属性的公开getterssetters

答案 5 :(得分:0)

你应该改变你的Object类..添加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;
}
}

并为'title'创建setter和getter .. 如果你想获得标题/作者,只需致电

Book.getAuthor();

答案 6 :(得分:0)

如果您不想为您的类设置getter / setter方法;您可以将访问修饰符定义为使用static关键字保护。例如: 在com.test包下 - 有两个类。一个是Book类,另一个是BookInSamePackage类。在Book类中;如果你将属性标题定义为受保护的静态字符串标题,那么在BookInSamePackage类中;你可以这样访问:'Book.title '。如果你想在另一个包的类中使用这个title属性;那么这个类需要扩展Book类,并且可以这样访问:另一个包的子类中的Book.title。