Оценка короткого замыкания Java

Если в строке указано только ОДИН значение, вы можете использовать concat()

. Вы можете заметить, что я выполнил преобразование в столбце datetime для сохранения формата.

Пример

Select A.ID
      ,column_value = concat([column_varchar],convert(varchar(25),[column_datetime],25),[column_int],[column_bit])
 From  YourTable A

Возвращает

1   1
2   2019-01-15 00:00:00.000
3   apple
4   0
5   2019-01-15 00:00:00.000
6   25
17
задан zengr 30 May 2012 в 22:09
поделиться

7 ответов

Урок по расширенной отладке №1:

Если вы столкнетесь с кажущейся невозможной ошибкой (например, с ошибкой, которая противоречит вашим знаниям о Java), сделайте следующее:

  • Проконсультируйтесь с авторитетным учебником (или, еще лучше, соответствующий стандарт), чтобы подтвердить, что ваше понимание не ошибочно. (В данном случае ваше понимание было правильным, и любой полуприличный учебник подтвердит это через минуту.)

  • Отметьте все глупые вещи, которые вы могли сделать, которые могли вызвать невозможную ошибку. Такие вещи, как невыполнение сохранения файла, невыполнение полной сборки, запуск старой / устаревшей версии приложения, нахождение в неправильном каталоге и т. Д.

Таким образом, научитесь немного сомневаться в себе.

6
ответ дан 30 November 2019 в 12:58
поделиться

Java имеет оценку короткого замыкания. Возможно, entry - это null, и поэтому entry.getKey() вызывает NullPointerException. Другая возможность заключается в том, что getAddress() либо возвращает null, либо имеет NullPointerException, происходящее где-то внутри (если это сложнее, чем простое утверждение return).

РЕДАКТИРОВАТЬ: я вижу ваше редактирование, где вы утверждаете, что:

Более того, невозможно выполнить perfectAgent.getAddress() ...

Но что, если perfectAgent.getAddress() будет успешно выполнено и вернет null? Видишь, что я имею в виду ...

7
ответ дан 30 November 2019 в 12:58
поделиться

Существует три ссылки, отличные от perfectAgent, которые могут иметь значение null:

  • perfectAgent.getAddress ()
  • entry
  • entry.getKey ()

Разбейте оператор или запустите его в отладчике.

1
ответ дан 30 November 2019 в 12:58
поделиться

If perfectAgent is genuinely null, that code won't throw an exception (at least assuming there aren't weird threading things going on, changing it from non-null to null half way through the expression). I would be utterly shocked if you could produce a short but complete program demonstrating it doing so.

So yes, your intuition is right - this shouldn't be a problem. Look elsewhere for the cause. I strongly suspect that perfectAgent isn't actually null, and that you're running into any of the other situations in that code which could cause an exception.

I suggest you try to extract that bit of code out into a short but complete example - if you can do so, I'll eat my metaphorical hat; if not, you'll hopefully find the problem while you attempt the extraction.

What makes you think that perfectAgent really is null? Try inserting this code before it:

if (perfectAgent == null)
{
    System.out.println("Yup, it's null");
}

Another very, very slim possibility is that you've run into a JIT bug - but I highly doubt it.

10
ответ дан 30 November 2019 в 12:58
поделиться

You ensure that perfectAgent is not null, so one or more of perfectAgent.getAddress() or entry or entry.getKey() must be null. Or getAddress() or getKey() are hitting an NPE in their implementation.

To debug this sort of thing, look first at the stack trace to pin down the location. This would tell you if it's happening in getAddress() or in getKey() or in the pasted code snippet that calls them. Next, if it's in this snippet, add some code before the if to test which is null. You can use good old System.err.println() or assertions. (If you use assertions, be sure to enable them with the java command's -enableassertions flag.)

Update: So my interpretation turned out to be wrong ... the problem presented two contradictory facts (there was an NPE on this line and yet the short-circuit should have happened) and I automatically assumed the first fact was true and the second false when in fact it was a different problem entirely due to turning off the auto-build in Eclipse. Duh! In debugging something "impossible" it helps to be radically skeptical.

2
ответ дан 30 November 2019 в 12:58
поделиться

Большая тайна. Я скопировал вашу строку кода и протестировал его с помощью perfectAgent == null , entry == null , entry.getKey () == null и их комбинаций: На моем тестовом стенде нет NPE (Java 1.6).

Какая бы это ни была досадная ошибка, я сомневаюсь, что она как-то связана с оценкой короткого замыкания. Если эта строка вызывает NPE, то, насколько я могу сказать, perfectAgent не равен нулю. Удачи и - покажите нам ошибку, как только вы ее поймаете :)

1
ответ дан 30 November 2019 в 12:58
поделиться

Попробуйте отформатировать свой код следующим образом:

if( 
  (perfectAgent != null) 
  && (
      perfectAgent.getAddress()
      .equals(
       entry.getKey()
      )
     ) 
  ) {

Это должно дать вам лучшую запись строки трассировки стека.

0
ответ дан 30 November 2019 в 12:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: