如何在Java中将类型作为方法参数传递 [英] How to pass a type as a method parameter in Java

查看:2744
本文介绍了如何在Java中将类型作为方法参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如何将类型作为参数传递(或声明为变量)?

In Java, how can you pass a type as a parameter (or declare as a variable)?

我不想传递类型的实例但类型本身(例如int,String等)。

I don't want to pass an instance of the type but the type itself (eg. int, String, etc).

在C#中,我可以这样做:

In C#, I can do this:

private void foo(Type t)
{
    if (t == typeof(String)) { ... }
    else if (t == typeof(int)) { ... }
}

private void bar()
{
    foo(typeof(String));
}

Java中是否有一种方法可以不传递实例类型为t?

或者我是否必须使用自己的int常量或枚举?

或者有更好的方法吗?

Is there a way in Java without passing an instance of type t?
Or do I have to use my own int constants or enum?
Or is there a better way?

编辑:这是foo的要求:

基于类型t,它生成一个不同的短xml字符串。

if / else中的代码将是非常小(一两行)并将使用一些私有类变量。

Here is the requirement for foo:
Based on type t, it generates a different short, xml string.
The code in the if/else will be very small (one or two lines) and will use some private class variables.

推荐答案

你可以传递 Class< T> in。

You could pass a Class<T> in.

private void foo(Class<?> cls) {
    if (cls == String.class) { ... }
    else if (cls == int.class) { ... }
}

private void bar() {
    foo(String.class);
}

更新:OOP方式取决于功能需求。最好的选择是定义 foo()的接口和实现 foo()的两个具体实现,然后只需调用 foo()关于你手边的实现。另一种方式可能是 Map< Class<?>,Action> ,您可以通过 actions.get(cls)。这很容易与接口和具体实现相结合: actions.get(cls).foo()

Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo() and two concrete implementations implementing foo() and then just call foo() on the implementation you've at hand. Another way may be a Map<Class<?>, Action> which you could call by actions.get(cls). This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo().

这篇关于如何在Java中将类型作为方法参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆