java 怎么设置 传 类,如何在Java中将类型作为方法参数传递

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

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

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));

}

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?

Edit: 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.

解决方案

You could pass a Class in.

private void foo(Class> cls) {

if (cls == String.class) { ... }

else if (cls == int.class) { ... }

}

private void bar() {

foo(String.class);

}

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, 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().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值