
一、相关知识JDK String的实现
1.1 String JDK 8的实现
class String {
char[] value;
// 构造函数会拷贝
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
// 无拷贝构造函数
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
}
1.2 String JDK 9及之后版本的实现
class String {
static final byte LATIN1 = 0;
static final byte UTF16 = 1;
byte code;
byte[] value;
// 无拷贝构造函数
String(byte[] value, byte coder) {
this.value = value;
this.coder = coder;
}
}
二、相关知识Unsafe
public class UnsafeUtils {
public static final Unsafe UNSAFE;
static {
Unsafe unsafe = null;
try {
Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeField.setAccessible(true);
unsafe = (Unsafe) theUnsafeField.get(null);
} catch (Throwable ignored) {
// ignored
}
UNSAFE = unsafe;
}
}
三、相关知识Trusted MethodHandles.Lookup
import static com.alibaba.fastjson2.util.UnsafeUtils.UNSAFE;
static final MethodHandles.Lookup IMPL_LOOKUP;
static {
Class lookupClass = MethodHandles.Lookup.class;
Field implLookup = lookupClass.getDeclaredField("IMPL_LOOKUP");
long fieldOffset = UNSAFE.staticFieldOffset(implLookup);
IMPL_LOOKUP = (MethodHandles.Lookup) UNSAFE.getObject(lookupClass, fieldOffset);
}
static MethodHandles.Lookup trustedLookup(Class objectClass) throws Exception {
return IMPL_LOOKUP.in(objectClass);
}
四、零拷贝构造String对象
4.1 JDK 8零拷贝构造String对象的实现
BiFunction<char[], Boolean, String> stringCreatorJDK8
= (char[] value, boolean share) -> new String(chars, boolean);
import com.alibaba.fastjson2.util.JDKUtils;
import java.util.function.BiFunction;
import java.lang.invoke.MethodHandles;
import static java.lang.invoke.MethodType.methodType;
MethodHandles.Lookup caller = JDKUtils.trustedLookup(String.class);
MethodHandle handle = caller.findConstructor(
String.class,
methodType(void.class, char[].class, boolean.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
caller,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, char[].class, boolean.class)
);
BiFunction<char[], Boolean, String> STRING_CREATOR_JDK8
= (BiFunction<char[], Boolean, String>)
callSite.getTarget().invokeExact();
4.2 JDK9及之后版本实现零拷贝构造String对象的实现
BiFunction<byte[], Byte, String> STRING_CREATOR_JDK11
= (byte[] value, byte coder) -> new String(value, coder);
import com.alibaba.fastjson2.util.JDKUtils;
import static java.lang.invoke.MethodType.methodType;
MethodHandles.Lookup caller = JDKUtils.trustedLookup(String.class);
MethodHandle handle = caller.findConstructor(
String.class,
methodType(void.class, byte[].class, byte.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
caller,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, byte[].class, Byte.class)
);
BiFunction<byte[], Byte, String> STRING_CREATOR_JDK11
= (BiFunction<byte[], Byte, String>)
callSite.getTarget().invokeExact();
4.3 快速构造String对象应用举例
stiatic BiFunction<char[], Boolean, String> STRING_CREATOR_JDK8 = ...
static BiFunction<byte[], Byte, String> STRING_CREATOR_JDK11 = ...
static String formatYYYYMMDD(LocalDate date) {
int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
int y0 = year / 1000 + '0';
int y1 = (year / 100) % 10 + '0';
int y2 = (year / 10) % 10 + '0';
int y3 = year % 10 + '0';
int m0 = month / 10 + '0';
int m1 = month % 10 + '0';
int d0 = dayOfMonth / 10 + '0';
int d1 = dayOfMonth % 10 + '0';
String str;
if (STRING_CREATOR_JDK11 != null) {
byte[] bytes = new byte[10];
bytes[0] = (byte) y0;
bytes[1] = (byte) y1;
bytes[2] = (byte) y2;
bytes[3] = (byte) y3;
bytes[4] = '-';
bytes[5] = (byte) m0;
bytes[6] = (byte) m1;
bytes[7] = '-';
bytes[8] = (byte) d0;
bytes[9] = (byte) d1;
str = STRING_CREATOR_JDK11.apply(bytes, JDKUtils.LATIN1);
} else {
char[] chars = new char[10];
chars[0] = (char) y1;
chars[1] = (char) y2;
chars[2] = (char) y3;
chars[3] = (char) y4;
chars[4] = '-';
chars[5] = (char) m0;
chars[6] = (char) m1;
chars[7] = '-';
chars[8] = (char) d0;
chars[9] = (char) d1;
if (STRING_CREATOR_JDK8 != null) {
str = STRING_CREATOR_JDK8.apply(chars, Boolean.TRUE);
} else {
str = new String(chars);
}
}
return str;
}
五、直接访问String对象内部成员
5.1 JDK 8快速访问value
static final Field FIELD_STRING_VALUE;
static final long FIELD_STRING_VALUE_OFFSET;
static {
Field field = null;
long fieldOffset = -1;
try {
field = String.class.getDeclaredField("value");
fieldOffset = UnsafeUtils.objectFieldOffset(field);
} catch (Exception ignored) {
FIELD_STRING_ERROR = true;
}
FIELD_STRING_VALUE = field;
FIELD_STRING_VALUE_OFFSET = fieldOffset;
}
public static char[] getCharArray(String str) {
if (!FIELD_STRING_ERROR) {
try {
return (char[]) UnsafeUtils.UNSAFE.getObject(
str,
FIELD_STRING_VALUE_OFFSET
);
} catch (Exception ignored) {
FIELD_STRING_ERROR = true;
}
}
return str.toCharArray();
}
5.2 JDK 9及之后版本直接访问coder & value
ToIntFunction<String> stringCoder = (String str) -> str.coder();
Function<String, byte[]> stringValue = (String str) -> str.value();
import com.alibaba.fastjson2.util.JDKUtils;
import static java.lang.invoke.MethodType.methodType;
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(String.class);
MethodHandle coder = lookup.findSpecial(
String.class,
"coder",
methodType(byte.class),
String.class
);
CallSite applyAsInt = LambdaMetafactory.metafactory(
lookup,
"applyAsInt",
methodType(ToIntFunction.class),
methodType(int.class, Object.class),
coder,
MethodType.methodType(byte.class, String.class)
);
ToIntFunction<String> STRING_CODER
= (ToIntFunction<String>) applyAsInt.getTarget().invokeExact();
MethodHandle value = lookup.findSpecial(
String.class,
"value",
methodType(byte[].class),
String.class
);
CallSite apply = LambdaMetafactory.metafactory(
lookup,
"apply",
methodType(Function.class),
methodType(Object.class, Object.class),
value,
methodType(byte[].class, String.class)
);
Function<String, byte[]> STRING_VALUE
= (Function<String, byte[]>) apply.getTarget().invokeExact();
5.3 直接访问举例
static Byte LATIN1 = 0;
static ToIntFunction<String> STRING_CODER = ...
static Function<String, byte[]> STRING_VALUE ...
byte[] buf = ...;
int off;
void writeString(string str) {
if (STRING_CODER != null && STRING_VALUE != null) {
// improved for JDK 9 LATIN1
int coder = stringCoder.apply(str);
if (coder == LATIN1) {
// str.getBytes(0, str.length, buf, off);
byte[] value = STRING_VALUE.apply(str);
System.arrayCopy(value, 0, buf, off, value.length);
return;
}
}
// normal logic
}
5.4 巧用String.getBytes方法
class String {
@Deprecated
public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
int j = dstBegin;
int n = srcEnd;
int i = srcBegin;
char[] val = value; /* avoid getfield opcode */
while (i < n) {
dst[j++] = (byte)val[i++];
}
}
}
static Byte LATIN1 = 0;
static ToIntFunction<String> STRING_CODER = ...
byte[] buf = ...;
int off;
void writeString(string str) {
if (STRING_CODER != null) {
// improved for JDK 9 LATIN1
int coder = STRING_CODER.apply(str);
if (coder == LATIN1) {
str.getBytes(0, str.length, buf, off);
return;
}
}
// normal logic
}
FASTJSON2项目使用了上面的技巧,其中JDKUtils和UnsafeUtils有上面技巧的实现:
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser