Недавно я столкнулся с этим сообщением в Vanilla #Java . Это не очень удобно писать Arrays.toString(arr);
, а затем импортировать java.util.Arrays;
все время.
Обратите внимание, что это не постоянное исправление любыми способами. Просто взломать, что упростит отладку.
Печать массива напрямую дает внутреннее представление и hashCode. Теперь все классы имеют Object
в качестве родительского типа. Итак, почему бы не взломать Object.toString()
? Без модификации класс Object выглядит следующим образом:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Что делать, если это было изменено на:
public String toString() {
if (this instanceof boolean[])
return Arrays.toString((boolean[]) this);
if (this instanceof byte[])
return Arrays.toString((byte[]) this);
if (this instanceof short[])
return Arrays.toString((short[]) this);
if (this instanceof char[])
return Arrays.toString((char[]) this);
if (this instanceof int[])
return Arrays.toString((int[]) this);
if (this instanceof long[])
return Arrays.toString((long[]) this);
if (this instanceof float[])
return Arrays.toString((float[]) this);
if (this instanceof double[])
return Arrays.toString((double[]) this);
if (this instanceof Object[])
return Arrays.deepToString((Object[]) this);
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Этот модифицированный класс можно просто добавить в путь класса, добавив в командной строке: -Xbootclasspath/p:target/classes
.
Теперь, когда доступ к deepToString(..)
с Java 5, toString(..)
можно легко изменить на deepToString(..)
, чтобы добавить поддержку массивов, которые содержат другие массивы.
Я нашел, что это довольно полезный взлом, и было бы здорово, если бы Java просто добавила это. Я понимаю потенциальные проблемы с очень большими массивами, поскольку представления строк могут быть проблематичными. Возможно, передайте что-то вроде System.out
или PrintWriter
для таких событий.
В принципе, Dog
предположительно является конструктором со свойством name
. EventEmitter.call(this)
, когда выполняется при создании экземпляра Dog
, добавляет свойства, объявленные из конструктора EventEmitter
, в Dog
.
Помните: конструкторы все еще являются функциями и могут по-прежнему использоваться как функции.
//An example EventEmitter
function EventEmitter(){
//for example, if EventEmitter had these properties
//when EventEmitter.call(this) is executed in the Dog constructor
//it basically passes the new instance of Dog into this function as "this"
//where here, it appends properties to it
this.foo = 'foo';
this.bar = 'bar';
}
//And your constructor Dog
function Dog(name) {
this.name = name;
//during instance creation, this line calls the EventEmitter function
//and passes "this" from this scope, which is your new instance of Dog
//as "this" in the EventEmitter constructor
EventEmitter.call(this);
}
//create Dog
var newDog = new Dog('furball');
//the name, from the Dog constructor
newDog.name; //furball
//foo and bar, which were appended to the instance by calling EventEmitter.call(this)
newDog.foo; //foo
newDoc.bar; //bar
EventEmitter.call(this);
Эта строка примерно эквивалентна вызову super () в языках с классическим наследованием.