检查参数是否是类特定静态字段的引用

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

Check if argument is a reference to a class' specific static field

问题

/*
 * 我想要:
 *
 * isCharacterCurrencySymbolReference(Character.CURRENCY_SYMBOL) 评估为 true
 *
 * 而像这样的:
 *
 * isCharacterCurrencySymbolReference(Character.LINE_SEPARATOR) 评估为 false
 *
 */
public static boolean isCharacterCurrencySymbolReference(Byte staticCharacterField)
{
    return Character.class.getField("CURRENCY_SYMBOL") == staticCharacterField.getFieldThisArgumentIsReferenceTo();
}
英文:

I want to check if a provided argument is a reference to a specific static field of a class, but want the method to be able to be passed the static reference directly and derive the Field property of the argument internally:

/*
 * I want:
 *
 * isCharacterCurrencySymbolReference(Character.CURRENCY_SYMBOL) to evaluate to true
 *
 * while something like:
 *
 * isCharacterCurrencySymbolReference(Character.LINE_SEPARATOR) to evaluate to false
 *
 */
public static boolean isCharacterCurrencySymbolReference(Byte staticCharacterField)
{
    return Character.class.getField("CURRENCY_SYMBOL") == staticCharacterField.getFieldThisArgumentIsReferenceTo();
}

Would something like that be possible or because the static reference is evaluated to a primitive byte at runtime make it impossible without the method just being passed a Field as an argument directly?

答案1

得分: 1

将它变成一个Byte而不是一个byte。由于Byte的实例是一个对象而不是一个原始类型,所以它应该可以工作。

英文:

Make it a Byte instead of a byte. Since an instance of a Byte is an object instead of a primitive, it should work.

答案2

得分: 0

因为在Java中,参数是按值传递的,所以方法只有所传参数的值,并且不能被用作指向其来源的引用。

英文:

Since arguments are pass-by-value in Java, a method only has the value of the argument it's passed and therefore cannot be used as a reference to where it originated from.

huangapple
  • 本文由 发表于 2020年5月3日 16:39:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61571714.html
匿名

发表评论

匿名网友

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

确定