GVKun编程网logo

java为什么使用TypeReference(java为什么使用包装类)

21

本文的目的是介绍java为什么使用TypeReference的详细情况,特别关注java为什么使用包装类的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解java为什么

本文的目的是介绍java为什么使用TypeReference的详细情况,特别关注java为什么使用包装类的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解java为什么使用TypeReference的机会,同时也不会遗漏关于android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences、C#string是value type还是reference type?、com.fasterxml.jackson.core.type.TypeReference的实例源码、Difference between SoftReference and WeakReference in Java的知识。

本文目录一览:

java为什么使用TypeReference(java为什么使用包装类)

java为什么使用TypeReference(java为什么使用包装类)

用途

在使用fastJson时,对于泛型的反序列化很多场景下都会使用到TypeReference,例如:

void testTypeReference() {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(9);
        list.add(4);
        list.add(8);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("a", list);
        System.out.println(jsonObj);

        List<String> list2 = jsonObj.getObject("a", new TypeReference<List<Integer>>(){});

        System.out.println(list2);
    }

输出

{"a":[1,9,4,8]}
[1, 9, 4, 8]

使用TypeReference可以明确的指定反序列化的类型,具体实现逻辑参考TypeReference的构造函数 

protected TypeReference(){
        Type superClass = getClass().getGenericSuperclass();

        Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];

        Type cachedType = classTypeCache.get(type);
        if (cachedType == null) {
            classTypeCache.putIfAbsent(type, type);
            cachedType = classTypeCache.get(type);
        }

        this.type = cachedType;
    }

解说

其中核心的方法是:getActualTypeArguments,它可以得到父类的反省类型

ParameterizedType是一个记录类型泛型的接口, 继承自Type,一共三方法:

  • Type[] getActualTypeArguments(); //返回泛型类型数组
  • Type getRawType(); //返回原始类型Type
  • Type getOwnerType(); //返回 Type 对象,表示此类型是其成员之一的类型。

例如 Map<String,String> 对应的ParameterizedType三个方法分别取值如下:

  • [class java.lang.String, class java.lang.String]
  • interface java.util.Map
  • null

例证

package JsonLearn;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class TypeReferencBaseLearn {
    public static class IntMap extends HashMap<String, Integer> {}

    void test1() {
        IntMap intMap = new IntMap();
        System.out.println("getSuperclass:" + intMap.getClass().getSuperclass());
        System.out.println("getGenericSuperclass:" + intMap.getClass().getGenericSuperclass());
        Type type = intMap.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType p = (ParameterizedType)type;
            for (Type t : p.getActualTypeArguments()) {
                System.out.println(t);
            }
        }
    }

    void test2() {
        Map<String, Integer> intMap = new HashMap<>();
        System.out.println("\ngetSuperclass:" + intMap.getClass().getSuperclass());
        System.out.println("getGenericSuperclass:" + intMap.getClass().getGenericSuperclass());
        Type type = intMap.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType p = (ParameterizedType)type;
            for (Type t : p.getActualTypeArguments()) {
                System.out.println(t);
            }
        }
    }

    void test3() {
        Map<String, Integer> intMap = new HashMap<String, Integer>(){};
        System.out.println("\ngetSuperclass:" + intMap.getClass().getSuperclass());
        System.out.println("getGenericSuperclass:" + intMap.getClass().getGenericSuperclass());
        Type type = intMap.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType p = (ParameterizedType)type;
            for (Type t : p.getActualTypeArguments()) {
                System.out.println(t);
            }
        }
    }

    public static void main(String[] args) {
        TypeReferencBaseLearn obj = new TypeReferencBaseLearn();
        obj.test1();
        obj.test2();
        obj.test3();
    }
}

输出

getSuperclass:class java.util.HashMap
getGenericSuperclass:java.util.HashMap<java.lang.String, java.lang.Integer>
class java.lang.String
class java.lang.Integer

getSuperclass:class java.util.AbstractMap
getGenericSuperclass:java.util.AbstractMap<K, V>
K
V

getSuperclass:class java.util.HashMap
getGenericSuperclass:java.util.HashMap<java.lang.String, java.lang.Integer>
class java.lang.String
class java.lang.Integer 

 

注意区分test3()中的:

Map<String, Integer> intMap = new HashMap<String, Integer>(){};

而不是

Map<String, Integer> intMap = new HashMap<String, Integer>;

后者是test2()

 

android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences

android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences

如果我具有Preference-Activity或-Fragment,则可以提供preference.xml文件来构建我的PreferenceScreen,并通过addPreferenceFromresource(R.xml.preference)进行显示.

然后可以通过PreferenceManager.getDefaultSharedPreferences(Context)检索更改的值.

我只是想知道是否可以将片段的默认首选项设置为默认值.

我希望有一个PreferenceFragment能够将其首选项(通过xml提供)存储在可以通过context.getSharedPreferences(“ customPrefName”,Context.MODE_PRIVATE)检索的Preferences中.
但是我在xml中找不到类似的东西

<PreferenceScreen android:prefName="customPrefName">...

解决方法:

如果要具有自定义首选项xml文件,则需要设置首选项名称,然后再将其从PreferenceFragment类的xml添加到屏幕.

public class CustomNamePreferenceFragment extends PreferenceFragment {

    private static final String PREF_FILE_NAME = "custom_name_xml";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PreferenceManager preferenceManager = getPreferenceManager();
        preferenceManager.setSharedPreferencesName(PREF_FILE_NAME);
        addPreferencesFromresource(R.xml.prefs);
        ... //rest of the code
    }
}

注意:您需要在onCreate()的超级调用之后和调用addPreferencesFromresource()方法之前设置共享首选项名称.

C#string是value type还是reference type?

C#string是value type还是reference type?

首先看代码:

           int a = 1;           
           int b = a;
           a = 2;           
           bool valOrRef = b == 2  ;//false;
登录后复制

  可以看出int类型是值类型,因为b并没有跟随a改变。

  再看下面代码:

            string str11 = "qa";            
            string str22 = str11;
            str11 = "qaz";            
            bool valOrRef2 = str22 == "qaz"; //false
登录后复制

  结果也是false,所以string 也是值类型 value type。

  再看下面代码:

            string str1 = "qaz";            
            string str2 = "qaz";            
            bool refequ = object.ReferenceEquals(str1, str2); //true
登录后复制

   refequ等于true,如果string真的是value type,那么refequ怎么可能为true,因为请看下面代码:

            int a = 1;            
            int b = 1;            
            bool refequ2 = object.ReferenceEquals(a, b);//false
登录后复制

  int是值类型,这是确定无疑的,声明了2个int变量。

  这便自相矛盾了,怎么解释,string看着像value type,但是又看着像reference type。

  微软:string是reference type。那么如何解释看着像value type 呢?

  请记住2点:

1)string对象,若值相同,则其引用地址相同。
2)string对象,若值不等,则其引用地址不等。

  分析以上代码:

            string str11 = "qa";//str11指向了内存addressA,数据为qa;
            string str22 = str11;//str22也指向内存addressA
            str11 = "qaz";//str11新指向了内存addressB,数据为qaz
            bool valOrRef2 = str22 == "qaz"; //false
登录后复制

总结:

   string最为显著的一个特点就是它具有恒定不变性:我们一旦创建了一个string,在managed heap 上为他分配了一块连续的内存空间,我们将不能以任何方式对这个string进行修改使之变长、变短、改变格式。所有对这个string进行各项操作而返回的string,实际上另一个重新创建的string,其本身并不会产生任何变化。

后记:
  string效率怎么样?

  string对象称为不可变的(只读)对象,因为一旦创建了该对象,就不能修改该对象的值。有的时候看来似乎修改了,实际是string经过了特殊处理,每次改变值时都会建立一个新的string对象,变量会指向这个新的对象,而原来的还是指向原来的对象,所以不会改变。这也是string效率低下的原因。

  

 以上就是C#string是value type还是reference type?的内容。

com.fasterxml.jackson.core.type.TypeReference的实例源码

com.fasterxml.jackson.core.type.TypeReference的实例源码

项目:echo    文件:ResourceDirectory.java   
private Map<String,String> populateDataFlows(Object item){
    Map<String,String> mapping = new HashMap<String,String>();
    LinkedHashMap<String,Object> linkedItem = (LinkedHashMap<String,Object>) item;
    ArrayList<LinkedHashMap>linkedMap = (ArrayList<LinkedHashMap>) linkedItem.get("item-Metadata");
    String mappingAsstring = null;
    for(LinkedHashMap hashmap : linkedMap){
        switch((String)hashmap.get("rel")){
        case "Mapping JSON": 
            mappingAsstring = (String)hashmap.get("val");
            break;
        }
    }
    mappingAsstring = mappingAsstring.replaceAll( "\\\\\"","\"");
    ObjectMapper mapper = new ObjectMapper();
    try {
        mapping = mapper.readValue(mappingAsstring,new TypeReference<Map<String,String>>(){});
    } catch (IOException e) {
        // Todo Auto-generated catch block
        e.printstacktrace();
    }
    return mapping;
}
项目:clemon    文件:ResourceController.java   
@SystemControllerLog(description="权限管理-资源列表")
@RequestMapping(value = "/data")
@ResponseBody
public String data(String params,HttpSession session) {
    try {
        ObjectMapper om = new ObjectMapper();
        Map<String,Object> map = new HashMap<String,Object>();
        // 当前只查询管理员
        if (!StringUtils.isEmpty(params)) {
            // 参数处理
            map = om.readValue(params,Object>>() {});
        }
        PagerModel<Resource > pg = resourceService.findPaginated(map);
        // 序列化查询结果为JSON
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("total",pg.getTotal());
        result.put("rows",pg.getData());
        return om.writeValueAsstring(result);
    } catch (Exception e) {
        e.printstacktrace();
        return "{ \"total\" : 0,\"rows\" : [] }";
    }
}
项目:fresco_floodlight    文件:StorageNotifyResource.java   
@Post("json")
public Map<String,Object> notify(String entity) throws Exception {
    List<StorageSourceNotification> notifications = null;
    ObjectMapper mapper = new ObjectMapper();
    notifications = 
        mapper.readValue(entity,new TypeReference<List<StorageSourceNotification>>(){});

    IStorageSourceService storageSource = 
        (IStorageSourceService)getContext().getAttributes().
            get(IStorageSourceService.class.getCanonicalName());
    storageSource.notifyListeners(notifications);

    HashMap<String,Object> model = new HashMap<String,Object>();
    model.put("output","OK");
    return model;
}
项目:javaOIDCMsg    文件:JsonNodeClaimTest.java   
@Test
public void shouldThrowIfAnExtraordinaryExceptionHappensWhenParsingAsGenericMap() throws Exception {
    JsonNode value = mock(ObjectNode.class);
    when(value.getNodeType()).thenReturn(JsonNodeType.OBJECT);

    JsonNodeClaim claim = (JsonNodeClaim) claimFromNode(value);
    JsonNodeClaim spiedClaim = spy(claim);
    ObjectMapper mockedMapper = mock(ObjectMapper.class);
    when(spiedClaim.getobjectMapper()).thenReturn(mockedMapper);
    JsonParser mockedParser = mock(JsonParser.class);
    when(mockedMapper.treeAsTokens(value)).thenReturn(mockedParser);
    when(mockedParser.readValueAs(ArgumentMatchers.any(TypeReference.class))).thenThrow(IOException.class);

    exception.expect(JWTDecodeException.class);
    spiedClaim.asMap();
}
项目:nakadi-producer-spring-boot-starter    文件:EventTransmissionService.java   
public NakadiEvent mapToNakadiEvent(final EventLog event) {
    final NakadiEvent nakadiEvent = new NakadiEvent();

    final NakadiMetadata Metadata = new NakadiMetadata();
    Metadata.setEid(convertToUUID(event.getId()));
    Metadata.setoccuredAt(event.getCreated());
    Metadata.setFlowId(event.getFlowId());
    nakadiEvent.setMetadata(Metadata);

    HashMap<String,Object> payloadDTO;
    try {
        payloadDTO = objectMapper.readValue(event.getEventBodyData(),new TypeReference<LinkedHashMap<String,Object>>() { });
    } catch (IOException e) {
        log.error("An error occurred at JSON deserialization",e);
        throw new UncheckedioException(e);
    }

    nakadiEvent.setData(payloadDTO);

    return nakadiEvent;
}
项目:flowing-retail    文件:MessageListener.java   
@StreamListener(target = Sink.INPUT)
@Transactional
public void messageReceived(String messageJson) throws Exception {
  Message<JsonNode> message = new ObjectMapper().readValue( //
      messageJson,//
      new TypeReference<Message<JsonNode>>() {});

  String type = "Event";
  if (message.getMessageType().endsWith("Command")) {
    type = "Command";
  }

  PastEvent event = new PastEvent( //
      type,//
      message.getMessageType(),//
      message.getTraceId(),//
      message.getSender(),//
      message.getPayload().toString());

  // save
  LogRepository.instance.addEvent(event);

  // and probably send to connected websocket (Todo: Not a good place for the code here!)
  simpMessageTemplate.convertAndSend("/topic/events",event);
}
项目:flowing-retail    文件:MessageListener.java   
/**
 * Handles incoming OrderPlacedEvents. 
 * 
 *  Using the conditional {@link StreamListener} from 
 * https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream-core-docs/src/main/asciidoc/spring-cloud-stream-overview.adoc
 * in a way close to what Axion
 *  would do (see e.g. https://dturanski.wordpress.com/2017/03/26/spring-cloud-stream-for-event-driven-architectures/)
 */
@StreamListener(target = Sink.INPUT,condition="payload.messageType.toString()=='OrderPlacedEvent'")
@Transactional
public void orderPlacedReceived(String messageJson) throws JsonParseException,JsonMappingException,IOException {
  Message<Order> message = new ObjectMapper().readValue(messageJson,new TypeReference<Message<Order>>(){});
  Order order = message.getPayload();

  System.out.println("New order placed,start flow. " + order);

  // persist domain entity
  repository.persistOrder(order);    

  // and kick of a new flow instance
  camunda.getRuntimeService().createMessageCorrelation(message.getMessageType())
    .processInstanceBusinessKey(message.getTraceId())
    .setvariable("orderId",order.getId())
    .correlateWithResult();
}
项目:trellis    文件:AbstractLdpResourceTest.java   
@Test
public void testPrefer() throws IOException {
    final Response res = target(RESOURCE_PATH).request()
        .header("Prefer","return=representation; include=\"" + Trellis.PreferServerManaged.getIRIString() + "\"")
        .accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();

    assertEquals(OK,res.getStatusInfo());

    final String entity = IoUtils.toString((InputStream) res.getEntity(),UTF_8);
    final Map<String,Object> obj = MAPPER.readValue(entity,Object>>(){});

    assertTrue(obj.containsKey("@context"));
    assertTrue(obj.containsKey("title"));
    assertFalse(obj.containsKey("mode"));
    assertTrue(obj.containsKey("created"));

    assertEquals("A title",(String) obj.get("title"));
}
项目:jetfuel-instagram    文件:Follows.java   
@Override
protected void mainFlow(UsecaseExecution<Parameters,InstagramResponse<List<User>>> execution) throws Exception {

    String endpoint = String.format(
            "https://api.instagram.com/v1/users/%s/follows?access_token=%s",execution.params.user_id,execution.params.access_token);

    URL url = new URL(endpoint);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    try {
        execution.result = MAPPER.readValue(is,new TypeReference<InstagramResponse<List<User>>>() {
        });
    } finally {
        is.close();
    }
    execution.result_type = UsecaseResultType.SUCCESS;
}
项目:jobson    文件:TestJobsAPI.java   
@Test
public void testCanGetJobInputs() throws IOException {
    final APIJobRequest req = REQUEST_AGAINST_FirsT_SPEC;

    final JobId jobId = generateAuthenticatedRequest(RULE,HTTP_JOBS_PATH)
            .post(json(req))
            .readEntity(APIJobCreatedResponse.class)
            .getId();

    final Response jobInputsResponse =
            generateAuthenticatedRequest(RULE,jobResourceSubpath(jobId + "/inputs"))
            .get();

    assertthat(jobInputsResponse.getStatus()).isEqualTo(OK);

    final String responseJson = jobInputsResponse.readEntity(String.class);

    final Map<JobExpectedInputId,JsonNode> inputsReturned =
            readJSON(responseJson,new TypeReference<Map<JobExpectedInputId,JsonNode>>() {});

    assertthat(inputsReturned).isEqualTo(req.getInputs());
}
项目:projectindoorweb    文件:EverythingControllerTest.java   
private long processEvaluationFileForBuilding(long buildingId) throws Exception {

        mockmvc.perform(mockmvcRequestBuilders.fileUpload("/position/processEvalFiles")
                .file(evaluationFile)
                .param("buildingIdentifier",String.valueOf(buildingId)))
                .andExpect(status().isOk());

        ResultActions getEvalFileResultActions = mockmvc.perform(get("/position/getEvalFilesForBuildingId?" +
                "buildingIdentifier=" + buildingId));
        getEvalFileResultActions.andExpect(status().isOk());
        String getEvalFileResult = getEvalFileResultActions.andReturn().getResponse().getContentAsstring();
        List<GetEvaluationFilesForBuilding> getEvaluationFilesForBuilding = (List<GetEvaluationFilesForBuilding>)
                this.objectMapper.readValue(getEvalFileResult,new TypeReference<List<GetEvaluationFilesForBuilding>>() {
                });
        assertTrue("The returned list of type " + GetEvaluationFilesForBuilding.class.getSimpleName() + " had an unexpected size.",getEvaluationFilesForBuilding.size() == 1);

        return getEvaluationFilesForBuilding.get(0).getId();

    }
项目:rubenlagus-TelegramBots    文件:GetFile.java   
@Override
public File deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<File> result = OBJECT_MAPPER.readValue(answer,new TypeReference<ApiResponse<File>>(){});
        if (result.getok()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error getting file",result);
        }
    } catch (IOException e) {
        throw new TelegramApiRequestException("Unable to deserialize response",e);
    }
}
项目:devops-cstack    文件:JsonConverter.java   
public static List<Environmentvariable> getEnvironmentvariables(String response) {
    List<Environmentvariable> environmentvariables = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    try {
        environmentvariables = mapper.readValue(response,new TypeReference<List<Environmentvariable>>() {
        });
    } catch (IOException e) {
        e.printstacktrace();
    }
    return environmentvariables;
}
项目:hibernate-types    文件:JacksonUtil.java   
public static <T> T fromString(String string,TypeReference<T> typeReference) {
    try {
        return OBJECT_MAPPER.readValue(string,typeReference);
    } catch (IOException e) {
        throw new IllegalArgumentException("The given string value: " + string + " cannot be transformed to Json object",e);
    }
}
项目:nuls    文件:JSONUtils.java   
/**
 * json string convert to map with javaBean
 */
public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz)
        throws Exception {
    Map<String,Map<String,Object>> map = OBJECT_MAPPER.readValue(jsonStr,T>>() {
            });
    Map<String,T> result = new HashMap<String,T>();
    for (Map.Entry<String,Object>> entry : map.entrySet()) {
        result.put(entry.getKey(),map2pojo(entry.getValue(),clazz));
    }
    return result;
}
项目:c4sg-services    文件:SlackClientServiceImpl.java   
protected <T> T readValue(JsonNode node,String findpath,TypeReference<?> typeReference) {
    try {
        if (findpath != null) {
            if (!node.has(findpath))
                return null;
            node = node.findpath(findpath);
        }
        return mapper.readValue(node.toString(),typeReference);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:rubenlagus-TelegramBots    文件:GetChatMember.java   
@Override
public ChatMember deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<ChatMember> result = OBJECT_MAPPER.readValue(answer,new TypeReference<ApiResponse<ChatMember>>(){});
        if (result.getok()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error getting chat member",e);
    }
}
项目:rubenlagus-TelegramBots    文件:SendDocument.java   
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,new TypeReference<ApiResponse<Message>>(){});
        if (result.getok()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error sending document",e);
    }
}
项目:plugin-prov-aws    文件:ProvAwsPriceImportResource.java   
/**
 * Read the spot region to the new format from an external JSON file.
 * 
 * @throws IOException
 *             When the JSON mapping file cannot be read.
 */
@postconstruct
public void initSpottoNewRegion() throws IOException {
    mapSpottoNewRegion.putAll(objectMapper.readValue(
            IoUtils.toString(new ClassPathResource(SPOT_TO_NEW_REGION_FILE).getInputStream(),StandardCharsets.UTF_8),String>>() {
                // nothing to extend
            }));
}
项目:cloudterm    文件:TerminalSocket.java   
private Map<String,String> getMessageMap(TextMessage message) {
    try {
        Map<String,String> map = new ObjectMapper().readValue(message.getPayload(),String>>() {
        });

        return map;
    } catch (IOException e) {
        e.printstacktrace();
    }
    return new HashMap<>();
}
项目:GitHub    文件:ObjectMappedTest.java   
@Test
public void jsonValueSingletonroundtrip() throws Exception {
  String json = "[1.4]";

  List<JsonValueCreator.Singleton> values =
      OBJECT_MAPPER.readValue(json,new TypeReference<List<JsonValueCreator.Singleton>>() {});

  check(OBJECT_MAPPER.writeValueAsstring(values)).is(json);
}
项目:GitHub    文件:JacksonParserFactory.java   
@Override
public HashMap<String,String> getStringMap(Object object) {
    try {
        TypeReference<HashMap<String,String>> typeRef
                = new TypeReference<HashMap<String,String>>() {
        };
        ObjectWriter objectWriter = mapper.writerFor(object.getClass());
        return mapper.readValue(objectWriter.writeValueAsstring(object),typeRef);
    } catch (Exception e) {
        e.printstacktrace();
    }
    return new HashMap<>();
}
项目:elasticsearch-jdbc    文件:JacksonjsONAdapter.java   
@Override
public JSONArray parseArray(String json) {
    try {
        List<Object> value = mapper.readValue(json,new TypeReference<List<Object>>() {
        });
        return new JacksonjsONArray(value);
    } catch (IOException e) {
        throw new JSONException(e);
    }
}
项目:liberty-outage-reporter    文件:CloudantLocationStore.java   
private static String readURLFromKubeSecretsFile(String secretsFile) throws IOException {
    String secretsJson = readKubeSecretsFiles(secretsFile);
    ObjectMapper mapper = new ObjectMapper();
    Map<String,Object> map;

    // convert JSON string to Map
    map = mapper.readValue(secretsJson,String>>(){});
    String url = (String) map.get("url");
    url = url.replaceFirst("https","http"); //Temporary hack until certificates are figured out.
    System.out.println("url: " + url);
    return url;
}
项目:neto    文件:NetoJsonStringToMapWebSocketDecoder.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx,WebSocketFrame frame) throws Exception {

    NetoExceptionMessage exceptionMessage;

    Map<String,Object> data = null;

    try {

        logger.error("{}",frame);

        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }

        if (frame instanceof TextWebSocketFrame) {
            data = objectMapper.readValue(((TextWebSocketFrame) frame).text(),Object>>() {});
        } else {
            exceptionMessage = new NetoExceptionMessage("Unsupported : " + frame.getClass().getName());
            data = objectMapper.convertValue(exceptionMessage,Map.class);
        }
    } catch (Exception e) {
        exceptionMessage = new NetoExceptionMessage(e.getMessage());
        data = objectMapper.convertValue(exceptionMessage,Map.class);
    }

    ctx.fireChannelRead(data);
}
项目:java-benchmark    文件:DeserJackson.java   
@Setup(Level.Trial)
public void benchSetup(BenchmarkParams params) {
    objectMapper = new ObjectMapper();
    objectMapper.registerModule(new AfterburnerModule());
    typeReference = new TypeReference<TestObject>() {
    };
    testJSON = TestObject.createTestJSON();
}
项目:fresco_floodlight    文件:AbstractSyncManager.java   
@Override
public <K,V>IStoreClient<K,V>
    getStoreClient(String storeName,TypeReference<K> keyType,TypeReference<V> valueType)
                           throws UnkNownStoreException {
    return getStoreClient(storeName,null,keyType,valueType,null);
}
项目:Practical-Real-time-Processing-and-Analytics    文件:ElasticSearchBolt.java   
public Map<String,Object> convertStringtoMap(String fieldValue) throws JsonParseException,IOException {
    System.out.println("Orignal value  "+ fieldValue);
    Map<String,Object> convertedValue = new HashMap<>();
    Map<String,Object> readValue = mapper.readValue(fieldValue,Object>>() {});

    convertedValue.put("ambient_temperature",Double.parseDouble(String.valueOf(readValue.get("ambient_temperature"))));
    convertedValue.put("photosensor",Double.parseDouble(String.valueOf(readValue.get("photosensor"))));
    convertedValue.put("humidity",Double.parseDouble(String.valueOf(readValue.get("humidity"))));
    convertedValue.put("radiation_level",Integer.parseInt(String.valueOf(readValue.get("radiation_level"))));
    convertedValue.put("sensor_uuid",readValue.get("sensor_uuid"));
    convertedValue.put("timestamp",new Date());

    System.out.println("Converted value  "+ convertedValue);
    return convertedValue;
}
项目:activiti-analytics-spring-boot    文件:AnalyticsConfig.java   
@SuppressWarnings("unchecked")
@Bean
public MappingConfiguration mappingConfiguration() {
    logger.debug("creating mappingConfiguration bean");
    MappingConfiguration mappingConf = new MappingConfiguration();
    try {
        URL endStateConfigUrl = Resources.getResource("mappingconfig/end-state-mapping.json");
        String endStateConfigJSON = Resources.toString(endStateConfigUrl,Charsets.UTF_8);
        mappingConf.setEndStateConfigMap((List<Map<String,Object>>) new ObjectMapper()
                .readValue(endStateConfigJSON,new TypeReference<List<Object>>() {
                }));

        URL allProcessConfigUrl = Resources.getResource("mappingconfig/all-processes-mapping-config.json");
        String allProcessConfigJSON = Resources.toString(allProcessConfigUrl,Charsets.UTF_8);
        mappingConf.setAllProcessConfigMap((Map<String,Object>) new ObjectMapper().readValue(allProcessConfigJSON,Object>>() {
                }));

        URL allTasksConfigUrl = Resources.getResource("mappingconfig/all-tasks-mapping-config.json");
        String allTasksConfigJSON = Resources.toString(allTasksConfigUrl,Charsets.UTF_8);
        mappingConf.setAllTasksConfigMap((Map<String,Object>) new ObjectMapper().readValue(allTasksConfigJSON,Object>>() {
                }));
    } catch (IOException e) {
        e.printstacktrace();
    }
    return mappingConf;
}
项目:fresco_floodlight    文件:AbstractSyncManager.java   
/**
 * The "real" version of getStoreClient that will be called by all
 * the others
 * @param storeName the store name
 * @param keyClass the key class
 * @param keyType the key type
 * @param valueClass the value class
 * @param valueType the value type
 * @param resolver the inconsistency resolver
 * @return a {@link DefaultStoreClient} using the given parameters.
 * @throws UnkNownStoreException
 */
public <K,V> IStoreClient<K,V>
        getStoreClient(String storeName,Class<K> keyClass,Class<V> valueClass,TypeReference<V> valueType,IInconsistencyResolver<Versioned<V>> resolver)
                               throws UnkNownStoreException {
    IStore<ByteArray,byte[]> store = getStore(storeName);
    IStore<K,V> serializingStore;
    if (valueType != null && keyType != null) {
        serializingStore = 
                new JacksonStore<K,V>(store,valueType);
    } else if (valueClass != null && keyClass != null) {
        serializingStore = 
                new JacksonStore<K,keyClass,valueClass);
    } else {
        throw new IllegalArgumentException("Must include type reference" +
                " or value class");
    }

    DefaultStoreClient<K,V> storeClient =
            new DefaultStoreClient<K,V>(serializingStore,resolver,this,keyType);
    return storeClient;
}
项目:rubenlagus-TelegramBots    文件:UnpinChatMessage.java   
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,new TypeReference<ApiResponse<Boolean>>(){});
        if (result.getok()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error unpinning chat message",e);
    }
}
项目:rkt-launcher    文件:List.java   
@Override
default ListOutput parse(final String output) {
  try {
    final java.util.List<io.honnix.rkt.launcher.model.Image> images =
        Json.deserializeSnakeCase(
            output,new TypeReference<java.util.List<io.honnix.rkt.launcher.model.Image>>() {
            });
    return ListOutput.builder()
        .images(images == null ? ImmutableList.of() : images)
        .build();
  } catch (IOException e) {
    throw new RktUnexpectedOutputException("Failed parsing JSON output",e);
  }
}
项目:qpp-conversion-tool    文件:ApmEntityIds.java   
/**
 * Given the file name,returns a {@link Set} of {@link String}s from the file.
 *
 * @param fileName The file to parse.
 * @return Set of Strings.
 */
private static Set<String> grabConfiguration(final String fileName) {
    TypeReference<Set<String>> setofStringsType = new TypeReference<Set<String>>() {};

    InputStream apmEntityIdsInput = ClasspathHelper.contextClassLoader().getResourceAsstream(fileName);

    return JsonHelper.readJson(apmEntityIdsInput,setofStringsType);
}
项目:qpp-conversion-tool    文件:JsonHelper.java   
/**
 * Read json file and return object type specified
 *
 * @param json content
 * @param valueType object type representation
 * @param <T> generic class type
 * @return Object of specified type
 * @throws JsonReadException if problems arise while attempting to parse the json input stream
 */
public static <T> T readJson(InputStream json,TypeReference<T> valueType) {
    T returnValue;
    try {
        returnValue = new ObjectMapper().readValue(json,valueType);
    } catch (IOException ex) {
        throw new JsonReadException(PROBLEM_PARSING_JSON,ex);
    }
    return returnValue;
}
项目:redg    文件:JsonFileNameProvider.java   
public JsonFileNameProvider(final File jsonFile) throws IOException {
    Objects.requireNonNull(jsonFile);
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String,JsonTableNameData>> typeReference = new TypeReference<HashMap<String,JsonTableNameData>>() {
    };
    mappings = mapper.readValue(jsonFile,typeReference);
}
项目:Tenable.io-SDK-for-Java    文件:InputControl.java   
/**
 * Sets list.
 *
 * @param list the list
 */
public void setList( List<?> list ) {
    ObjectMapper mapper = new ObjectMapper();

    try {
        this.list = mapper.readValue(list.toString(),new TypeReference<List<Dropdown>>() {} );
    } catch( Exception e) {
        this.list = new ArrayList<String>();
        this.list = list;
    }
}
项目:rubenlagus-TelegramBots    文件:SendGame.java   
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,new TypeReference<ApiResponse<Message>>(){});
        if (result.getok()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error sending game",e);
    }
}
项目:cmc-claim-store    文件:JsonMapper.java   
public <T> T fromJson(String value,TypeReference<T> typeReference) {
    try {
        return objectMapper.readValue(value,typeReference);
    } catch (IOException e) {
        throw new InvalidApplicationException(
            String.format(DESERIALISATION_ERROR_MESSAGE,typeReference.getType()),e
        );
    }
}
项目:StubbornJava    文件:JsonTest.java   
@Test
public void parseShouldNotFailOnExtraFields() {
    // {{start:fromJsonExtraFields}}
    String rawJson = Resources.asstring("json-test/extra-fields.json");
    Message message = Json.serializer().fromJson(rawJson,new TypeReference<Message>() {});
    // {{end:fromJsonExtraFields}}

    assertEquals("Happy New Year!",message.getMessage());
    assertEquals(LocalDate.of(2017,1,1),message.getDate());

    String actualJson = Json.serializer().toString(message);
    assertEquals(message,Json.serializer().fromJson(actualJson,new TypeReference<Message>() {}));
}

Difference between SoftReference and WeakReference in Java

Difference between SoftReference and WeakReference in Java

【Java】What''s the difference between SoftReference and WeakReference in Java

java

原文

What''s the difference between SoftReference and WeakReference in Java?

From Understanding Weak References, by Ethan Nicholas:

引言

在学习JVM的过程中大概率会看到类似 SoftReferenceWeakReference的字样,本部分挑选了Stack Flow 上的高赞回答进行整理。

Understanding Weak References

Understanding Weak References

虽然是一篇2006年的博客,但是写的非常好,并且至今也依然有不小的价值,这里简单翻译和提取一下这篇文章的内容。

前面一大段可以跳过,这里直接进入正题。

Now, I''m not suggesting you need to be a weak reference expert to qualify as a decent Java engineer. But I humbly submit that you should at least _know what they are_ -- otherwise how will you know when you should be using them? Since they seem to be a little-known feature, here is a brief overview of what weak references are, how to use them, and when to use them.

现在,我并不是说你需要成为一个参考资料专家,才有资格成为一个体面的Java工程师。但我谦虚地认为,你至少应该知道它们是什么 -- 否则你怎么会知道什么时候应该使用它们?由于它们似乎是一个鲜为人知的特性,这里简要介绍一下什么是弱引用,如何使用它们,以及何时使用它们。

Strong references

首先了解一下强引用,任何的new操作都是一个强引用:

StringBuffer buffer = new StringBuffer();
If an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection.

如果一个对象具备强引用,并且引用链可到达,那么垃圾回收器就没有资格进行回收。

When strong references are too strong

这部分大段文字描述的含义表明,有时候设计系统会把一些强引用对象放到HashMap这样的集合容器当中,它长的像这样:

serialNumberMap.put(widget, widgetSerialNumber);

表面上看这似乎工作的很好,但是我们必须知道(有100%的把握)何时不再需要这个对象,一旦把这个对象溢出,很有可能存在隐藏的内存泄漏或者强引用无法释放导致无法垃圾回收的问题。

强引用的另外一个问题是缓存,假设你有一个需要处理用户提供的图片的应用程序,你想要利用缓存来减少图像加载带来的磁盘开销,同时要避免两份一模一样的图像同时存在内存当。

对于普通的强引用来说,这个引用本身就会迫使图像留在内存中,这就要求你(就像上面一样)以某种方式确定何时不再需要内存中的图像,并将其从缓存中删除,这样它就有资格被垃圾回收。

最要命的是这种情况下甚至需要考虑垃圾回收器的工作行为。

Weak references

弱引用:简单来说是一个不够强大的引用,不足以迫使一个对象留在内存中。弱引用可以让程序员根据垃圾回收器的行为大致估算引用的生命周期。换句话说,弱引用肯定会在下一次垃圾收集器给回收掉,程序员无需担心类似强引用传递的问题。

在Java当中,通常用java.lang.ref.WeakReference类来表示。

public class Main {
    public static void main(String[] args) {
     
        WeakReference<String> sr = new WeakReference<String>(new String("hello"));
         
        System.out.println(sr.get());
        System.gc();                //通知JVM的gc进行垃圾回收
        System.out.println(sr.get());
    }
}/**输出结果:
hello
null
**/

注意被弱引用关联的对象是指只有弱引用与之关联,如果存在强引用同时与之关联,则进行垃圾回收时也不会回收该对象(软引用也是如此)

ReferenceQueue 应用

此外,弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被JVM回收,这个引用就会被加入到与之关联的引用队列中。

 @Test  
    public void referenceQueueUse() throws InterruptedException {  
        Object value = new Object();  
        Map<Object, Object> map = new HashMap<>();  
        ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<>();  
        for(int i = 0;i < 10000;i++) {  
            byte[] bytes = new byte[1024 * 1024];  
            WeakReference<byte[]> weakReference = new WeakReference<byte[]>(bytes, referenceQueue);  
            map.put(weakReference, value);  
        }  
        // 使用主线程观察 referenceQueue 的对象回收比较麻烦  
        Thread thread = new Thread(() -> {  
            try {  
                int cnt = 0;  
                WeakReference<byte[]> k;  
                // 等待垃圾回收  
                while((k = (WeakReference) referenceQueue.remove()) != null) {  
                    System.out.println((cnt++) + " 被回收了:" + k);  
                }  
            } catch(InterruptedException e) {  
                //结束循环  
            }  
        });  
//        thread.setDaemon(true);  
        thread.start();  
        thread.join();  
    }/**  
     0 被回收了:java.lang.ref.WeakReference@138caeca  
     1 被回收了:java.lang.ref.WeakReference@3402b4c9  
     2 被回收了:java.lang.ref.WeakReference@75769ab0  
     3 被回收了:java.lang.ref.WeakReference@2e23c180  
     4 被回收了:java.lang.ref.WeakReference@4aaae508  
     5 被回收了:java.lang.ref.WeakReference@3e84111a  
     6 被回收了:java.lang.ref.WeakReference@2cc04358  
     7 被回收了:java.lang.ref.WeakReference@45bb2aa1  
     8 被回收了:java.lang.ref.WeakReference@1639f93a  
     9 被回收了:java.lang.ref.WeakReference@f3021cb  
     */

上面的代码执行之后会触发垃圾回收,对象引用变为null就意味着对象被垃圾回收,WeakHashMap必须删除这种失效的条目,以避免持有不断增加的死的WeakReference。

在 WeakReference 中传入 ReferenceQueue,在引用失效的时候会被推入到ReferenceQueue当中。

在类weakHashMap中的使用

实际上weakHashMap就是使用weakReference当作key来进行数据的存储,所以key被gc之后响应的gc也可以移除掉。

WeakHashMap Weak在于Key而非Value,WeakHashMap的Key 没有其他强引用时,这些key就可能被回收,且WeakHashMap可能会回收这些Key对应的键值对。

这里举个比较容易出错的例子,那就是String 本身为对象,但是如果是 String xx = "xxx"这样的定义方式,由于key会被加载常量池当中自动获得强引用,实际上不会被垃圾回收。

@Test  
    public void weakHashMap(){  
        WeakHashMap<String, String> map = new WeakHashMap<>();  
        // 下面的注释说明 value 对于 WeakHashMap 过期没有任何影响,不管它是否在常量池当中有强引用。  
        String value = new String("value");  
//        String value = "value";  
  
        // new String 此时编译器无法感知,编译阶段无法提前感知,没有强引用保留。  
//        map.put(new String("key"), value); // {key=value}、  
  
        // 对于可在编译阶段确定的字符串,系统的字符串常量池会直接记录它,自动保留对它的强引用  
        map.put("key", value); // {key=value}  
        System.out.println(map);  
  
        System.gc();  
        System.runFinalization();  
  
        System.out.println(map);  
    }/**运行结果:  
     如果使用 new String("key") 则为下面的结果  
     {key=value}  
     {}  
     由于直接使用了字符串字面量“key”,造成了系统对“key”字符串的缓存,对其施加了强引用,因此GC未能销毁此实例  
     {key=value}  
     {key=value}     */

再看看下面的方法,可以看到如果让key,value 的引用同时使用一个引用,value实际使用的还是强引用(阅读源码也可以了解),由于Key和Value都存在强引用,所以这种情况下也会出现key无法回收的问题:

/**  
 * 模拟 Intern 方法  
 * @param <T>  
 */  
class SimulaIntern<T> {  
    private WeakHashMap<T, T> weakHashMap = new WeakHashMap<T, T>();  
  
    /**  
     * 修复之后的对象使用  
     */  
    private WeakHashMap<String, MyObject> weakHashMapFix = new WeakHashMap<>();  
  
    /**  
     * 此方法存在问题  
     * @description 此方法存在问题  
     * @param item  
     * @return T  
     * @author xander  
     * @date 2023/6/16 14:48  
     */    public T intern(T item){  
        if(weakHashMap.get(item) != null){  
            return weakHashMap.get(item);  
        }  
        // 根源在于这里的 put, 对于 key 来说是弱引用,但是 value 依旧是强引用保留  
        weakHashMap.put(item, item);  
        return item;  
    }  
  
    public MyObject intern(String key, MyObject value) {  
        MyObject object = weakHashMapFix.get(key);  
        if (object != null) {  
            return object;  
        }  
        weakHashMapFix.put(key, value);  
        return value;  
    }  
  
    public void print(){  
        System.out.println("weakHashMap => "+ weakHashMap);  
        System.out.println("weakHashMapFix => "+weakHashMapFix);  
    }  
  
}  
  
class MyObject{  
  
}  
  
@Test  
public void testWeakMap(){  
    // intern 存在问题  
    SimulaIntern<String> testPool = new SimulaIntern<>();  
    testPool.intern(new String("testPool"));  
    testPool.print();  
    System.gc();  
    System.runFinalization();  
    testPool.print();  
  
    // 可以正常清理,实际上就是把 k 和 value 两者进行拆分  
    SimulaIntern simulaIntern = new SimulaIntern();  
    simulaIntern.intern(new String("name"), new MyObject());  
    simulaIntern.print();  
    System.gc();  
    System.runFinalization();  
    simulaIntern.print();  
}/**运行结果:  
 // 无法正常清理  
 weakHashMap => {testPool=testPool}  
 weakHashMap => {testPool=testPool}  
 // 修改之后, 可以正常清理,实际上就是把 k 和 value 两者进行拆分  
 weakHashMapFix => {name=com.zxd.interview.weakref.WeakReferenceTest$MyObject@1936f0f5}  
 weakHashMapFix => {}*/

Soft references

软引用和弱引用的区别是,弱引用在没有强引用加持的情况下,通常必然会在下一次垃圾回收给清理掉,但软引用则稍微强一些,一般会坚持更长的时间,一般情况下如果内存足够软引用基本会被保留。

所以软引用的特征是:只要内存供应充足,Soft reachable对象通常会被保留。如果既担心垃圾回收提前处理掉对象,又担心内存消耗的需求,就可以考虑软引用。

Phantom references

虚引用和软引用和弱引用完全不一样,它的 get 方法经常返回 Null,虚引用的唯一用途是跟踪什么时候对象会被放入到引用队列,那么这种放入引用队列的方式和弱引用有什么区别?

主要的区别是入队的时间。WeakReference在它所指向的对象变为弱引用(无强引用)的时候会被推入到队列,因为可以在 queue 中获取到弱引用对象,该对象甚至可以通过非正统的finalize()方法 "复活",但WeakReference仍然是死的。

PhantomReference只有在对象被从内存中物理删除时才会被排队,而且get()方法总是返回null,主要是为了防止你能够 "复活 "一个几乎死去的对象。所以 PhantomReference 会有什么用:

  • 它们允许你准确地确定一个对象何时从内存中删除。
  • PhantomReferences避免了finalize()的一个基本问题。

第一点准确的确定一个对象何时删除,造某些大内存占用的情况下可以实现等待垃圾回收再加载下一个大内存对象防止OOM。

第二点finalize()方法可以通过为对象创建新的强引用来 "复活 "它们,但是虚引用可以很大概率避免对象复活。当一个PhantomReference被排队时,绝对没有办法获得现在已经死亡的对象的指针,该对象可以在第一个垃圾收集周期中被发现可以幻象地到达时被立即清理掉。

Stack Flow 的答案

这些答案基本都来自上面提到的博客相同,这里不再过多赘述。

Weak references

A _weak reference_, simply put, is a reference that isn''t strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector''s ability to determine reachability for you, so you don''t have to do it yourself. You create a weak reference like this

WeakReference weakWidget = new WeakReference(widget);

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn''t strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

...

Soft references

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

SoftReferences aren''t required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

最后的补充部分简单翻译一下

And Peter Kessler added in a comment:

下面是评论中的一些补充

The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn''t pressure on the available memory.

Sun JRE对待SoftReferences的方式与WeakReferences不同。如果可用内存并且此时没有使用压力,会尝试保留被SoftReference引用的对象。

One detail: the policy for the "-client" and "-server" JRE''s are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.

"-client "和"-server "JRE的策略是不同的:

  • -client:JRE试图通过优先清除SoftReferences而不是扩展堆来保持你的内存。
  • -server:JRE则试图通过优先扩展堆(如果可能)而不是清除SoftReferences来保持你的性能

写在最后

以上就是“What''s the difference between SoftReference and WeakReference in Java”的翻译,弱引用、虚引用、软引用这些内容更推荐阅读相关应用源码。

我们今天的关于java为什么使用TypeReferencejava为什么使用包装类的分享已经告一段落,感谢您的关注,如果您想了解更多关于android-从PreferenceActivity或PreferenceFragment中的资源添加特定的命名SharedPreferences、C#string是value type还是reference type?、com.fasterxml.jackson.core.type.TypeReference的实例源码、Difference between SoftReference and WeakReference in Java的相关信息,请在本站查询。

本文标签: