[英]In Java, can I create an object with a name passed by a String?
我想做这样的事情:
Creator method = new Creator();
method.addSubject("example");
class Creator{
public void addSubject(String subjName) {
//here is the issue
subjName = new Subject(subjName);
}
}
class Subject {
private String name;
public Subject(String newName) {
name = newName;
}
}
因此,我希望称为Creator的类能够创建Subjects,但我需要通过向其传递一个具有我要调用这些主题的名称的String来做到这一点。 我怎样才能做到这一点?
编辑:澄清一下,类“ Creator”具有一个称为“ addSubject”的方法。 在程序的主要方法中,我有一个创建者的对象,称为“方法”(可能应该选择一个更好的示例名称)。 那么,只需通过将方法“ addSubject”传递给我想要Subject对象的那些对象的名称,Creator的这个对象就可以使另一个类“ Subject”的对象吗?
Edit2:这是我想要的伪代码:
Main method:
Initialize Creator object
Command line for program takes arguments
Pass these arguments to creator object
Creator Object:
Takes command line argument in the form of string and makes a new object of the class Subject by the name of the String
我认为您想创建一个只想使用名称的类的新对象。
是吗?
因此,您可以执行此操作(Java 7)。
try { // you need to provide the default constructor! Object newInstance = Class.forName( "your.package.YourClassName" ).newInstance(); } catch ( ClassNotFoundException | IllegalAccessException | InstantiationException exc ) { exc.printStackTrace(); }
如果使用的Java版本是7之前的版本,则需要使用3个catch语句,一个用于ClassNotFoundException,一个用于IllegalAccessException,一个用于InstantiationException。
编辑:我想我现在明白了。 您想要使用传递给该方法的名称来创建Subject的实例。 您可以使用HashMap进行模拟。
就像是:
import java.util.*;
class Creator{
private Map<String, Subject> map = new HashMap<String, Subject>();
public void addSubject(String subjName) {
map.put( subjName, new Subject(subjName) );
}
public Subject getSubject(String subjName) {
return map.get(subjName);
}
}
class Subject {
private String name;
public Subject(String newName) {
name = newName;
}
@Override
public String toString() {
return name;
}
}
// using...
Creator method = new Creator();
method.addSubject("example");
// prints example
System.out.println( method.getSubject("example") );
// prints null, since there is not a value associeted to the "foo"
// key in the map. the map key is your "instance name".
System.out.println( method.getSubject("foo") );
这是行不通的:
subjName = new Subject(subjName);
subjName
是一个字符串,但是new Subject()
当然是一个Subject
怎么样
Subject myNewSubject = new Subject(subjName);
当然,我想您真正想要的是将该Subject
传递到某个地方(也许到Collection
?),但是您的问题没有弄清楚,因此我将其保留。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.