可以在Java中将一个类存储在变量中吗?

huangapple go评论70阅读模式
英文:

Is it possible to store a class in a variable in Java?

问题

我正在尝试做类似以下的事情:

class test {
  Class c;
  c[] array = new c[0];

  test(Class c_) {
   c = c_;
  }
}

这是为了使其可以通用,并且无论我在类test中放入哪个类,都可以正常工作。我已经尝试过这个确切的方法,但似乎不起作用。这种可能性存在吗?我也在使用Processing IDE,如果这有什么意义的话。

英文:

I'm trying to do something like:

class test {
  Class c;
  c[] array = new array[0];

  test(Class c_) {
   c = c_;
  }
}

It's so that it can be used generally, and that whatever class I put in the class test works. I've tried this exact thing already, but it doesn't seem to work. Is there any way this is possible? I'm also using the IDE Processing if that means anything.

答案1

得分: 3

是的和不是的。是的,可以动态创建一个数组,但不能使用您的语法(而且您应该使用泛型类型)。另外,请注意 Java 数组具有固定的长度(因此零元素数组没有多大用处)。而且 Java 类名以大写字母开头。像这样,

class Test<T> {
    private T[] array;

    @SuppressWarnings("unchecked")
    Test(Class<T> c, int len) {
        array = (T[]) Array.newInstance(c, len);
    }

    public void set(int p, T v) {
        array[p] = v;
    }

    public T[] getArray() {
        return array;
    }
}

然后是如何基本使用它的示例,

public static void main(String[] args) {
    int size = 5;
    Test<String> t = new Test<>(String.class, size);
    for (int i = 0; i < size; i++) {
        t.set(i, String.valueOf(i));
    }
    System.out.println(Arrays.toString(t.getArray()));
}

输出结果为

[0, 1, 2, 3, 4]
英文:

Yes, and no. Yes it is possible to dynamically create an array, but not with your syntax (and you should be using a generic type). Also, note that Java arrays have a fixed length (so a zero element array is not very useful). And Java class names start with a capital letter. Something like,

class Test&lt;T&gt; {
	private T[] array;

	@SuppressWarnings(&quot;unchecked&quot;)
	Test(Class&lt;T&gt; c, int len) {
		array = (T[]) Array.newInstance(c, len);
	}

	public void set(int p, T v) {
		array

= v; } public T[] getArray() { return array; } }

Then a basic demonstration of using it,

public static void main(String[] args) {
	int size = 5;
	Test&lt;String&gt; t = new Test&lt;&gt;(String.class, size);
	for (int i = 0; i &lt; size; i++) {
		t.set(i, String.valueOf(i));
	}
	System.out.println(Arrays.toString(t.getArray()));
}

Outputs

[0, 1, 2, 3, 4]

答案2

得分: -3

  • 类是创建对象的蓝图
  • 它在内存中没有实际存在
  • 它的实例存在,它们可以被存储
  • 所以,如果类在内存中没有存在,它不能被保存在变量中
英文:
  • class is blueprint to create object
  • it does not have a physical existence in memory
  • its instances have the existence they can be stored
  • so if class doesn't have existence in memory it cannot be saved in
    variables

huangapple
  • 本文由 发表于 2020年9月18日 07:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63947511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定