I have created 2 packages with classes like
我创建了2个类包的类
pakage1.class.files
|- ClassA;
|- ClassB;
pakage2.class.files
|- ClassC;
But i want to call the code as follows
但我想调用代码如下
public class ClassC
{
public void method1()
{
pakage1.class.files.ClassA var1 = new pakage1.class.files.ClassA();
}
}
But i want to pass "pakage1.class.files.ClassA" as variable like
但我想传递“pakage1.class.files.ClassA”作为变量
public class ClassC
{
public string CL1 = "pakage1.class.files.ClassA";
public void method1()
{
CL1 var1 = new CL1();
}
}
Kindly Help me...
请帮助我......
2 个解决方案
#1
1
No, you can't do this. Variable types have to be known at compile time.
不,你不能这样做。必须在编译时知道变量类型。
You could use:
你可以使用:
Class<?> clazz = Class.forName(className);
Object object = clazz.newInstance();
... but then of course you'd have to use reflection to get at any of the members. You won't have a variable of that type.
...但当然你必须使用反射来获得任何成员。你不会有这种类型的变量。
EDIT: Of course you don't need to have the fully-qualified name everywhere in your code. You can use import
statements for that:
编辑:当然,您不需要在代码中的任何位置拥有完全限定的名称。您可以使用import语句:
// Please don't include "class" as part of your package name...
import package1.class.files.ClassA;
public class ClassC {
public void method1() {
ClassA var1 = new ClassA();
}
}
... which isn't really the same thing, of course... but it may help you anyway.
......当然,这不是一回事......但无论如何它可能对你有所帮助。
#2
0
CL1 var1 = new CL1();
this is an error in java. CL1 is the identifier for a variable, not a data type hence you cannot use CL1 as a type when creating variables.
这是java中的错误。 CL1是变量的标识符,而不是数据类型,因此在创建变量时不能将CL1用作类型。
#1
1
No, you can't do this. Variable types have to be known at compile time.
不,你不能这样做。必须在编译时知道变量类型。
You could use:
你可以使用:
Class<?> clazz = Class.forName(className);
Object object = clazz.newInstance();
... but then of course you'd have to use reflection to get at any of the members. You won't have a variable of that type.
...但当然你必须使用反射来获得任何成员。你不会有这种类型的变量。
EDIT: Of course you don't need to have the fully-qualified name everywhere in your code. You can use import
statements for that:
编辑:当然,您不需要在代码中的任何位置拥有完全限定的名称。您可以使用import语句:
// Please don't include "class" as part of your package name...
import package1.class.files.ClassA;
public class ClassC {
public void method1() {
ClassA var1 = new ClassA();
}
}
... which isn't really the same thing, of course... but it may help you anyway.
......当然,这不是一回事......但无论如何它可能对你有所帮助。
#2
0
CL1 var1 = new CL1();
this is an error in java. CL1 is the identifier for a variable, not a data type hence you cannot use CL1 as a type when creating variables.
这是java中的错误。 CL1是变量的标识符,而不是数据类型,因此在创建变量时不能将CL1用作类型。