下面列出了怎么用java.lang.reflect.Type的API类实例代码及写法,或者点击链接到github查看源代码。
public Type onParameterizdType(ParameterizedType p, Class sup) {
Class raw = (Class) p.getRawType();
if(raw==sup) {
// p is of the form sup<...>
return p;
} else {
// recursively visit super class/interfaces
Type r = raw.getGenericSuperclass();
if(r!=null)
r = visit(bind(r,raw,p),sup);
if(r!=null)
return r;
for( Type i : raw.getGenericInterfaces() ) {
r = visit(bind(i,raw,p),sup);
if(r!=null) return r;
}
return null;
}
}
private <T> DataHandler getHandlerForObject(T obj,
Class<T> cls, Type genericType,
Annotation[] anns,
String mimeType) {
MediaType mt = JAXRSUtils.toMediaType(mimeType);
mc.put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, this);
MessageBodyWriter<T> r = null;
try {
r = mc.getProviders().getMessageBodyWriter(cls, genericType, anns, mt);
} finally {
mc.put(ProviderFactory.ACTIVE_JAXRS_PROVIDER_KEY, null);
}
if (r == null) {
org.apache.cxf.common.i18n.Message message =
new org.apache.cxf.common.i18n.Message("NO_MSG_WRITER",
BUNDLE,
cls);
LOG.severe(message.toString());
throw ExceptionUtils.toInternalServerErrorException(null, null);
}
return new MessageBodyWriterDataHandler<T>(r, obj, cls, genericType, anns, mt);
}
@Override
public long getSize(ITemplate template, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
if (template.getText()!=null){
String agreementData;
try {
agreementData = (xmlParser == null)?
defaultParser.getSerializedData(template.getText()):
xmlParser.getSerializedData(template.getText());
serializedData = (new String(HEADER + agreementData)).getBytes();
} catch (ParserException e) {
catchedException = e;
}
}else {
logger.error("Error marshalling data agreement text is null");
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
return serializedData.length;
}
/**
* get the type of generic
* @param type
* @param i
* @return
*/
public static Class<?> getClass(Type type, int i) {
if (type instanceof ParameterizedType) {
return getGenericClass((ParameterizedType) type, i);
} else if (type instanceof GenericArrayType) {
return (Class) ((GenericArrayType) type).getGenericComponentType();
} else if (type instanceof TypeVariable) {
return getClass(((TypeVariable) type).getBounds()[0], 0);
} else if (type instanceof WildcardType) {
WildcardType wuleType = (WildcardType) type;
if (null != wuleType.getUpperBounds()[0]) {
return getClass(wuleType.getUpperBounds()[0], 0);
} else {
return getClass(wuleType.getLowerBounds()[0], 0);
}
} else if (type instanceof Class) {
return (Class<?>) type;
} else {
return (Class<?>) type;
}
}
@Override
public String toString(Type type, T value, Map<String, String> attributes) {
requireNonNull(type, "type cannot be null");
if (value == null) {
return null;
}
@SuppressWarnings("unchecked")
JaxbPool jaxbPool = getJaxbPool((Class<T>) type);
try (Handle<Marshaller> handle = jaxbPool.borrowMarshaller()) {
Marshaller marshaller = handle.get();
StringWriter stringWriter = new StringWriter();
marshaller.marshal(value, stringWriter);
return stringWriter.toString();
} catch (JAXBException e) {
throw new IllegalArgumentException("Unable to convert " + value.getClass().getName() + " to xml using jaxb", e);
}
}
@Override
@SuppressWarnings("unchecked")
public void encode (Object object, Type bodyType, RequestTemplate template) throws EncodeException {
String contentTypeValue = getContentTypeValue(template.headers());
val contentType = ContentType.of(contentTypeValue);
if (!processors.containsKey(contentType)) {
delegate.encode(object, bodyType, template);
return;
}
Map<String, Object> data;
if (MAP_STRING_WILDCARD.equals(bodyType)) {
data = (Map<String, Object>) object;
} else if (isUserPojo(bodyType)) {
data = toMap(object);
} else {
delegate.encode(object, bodyType, template);
return;
}
val charset = getCharset(contentTypeValue);
processors.get(contentType).process(template, charset, data);
}
@SuppressWarnings("Duplicates")
@Override
public List<TwitterAppStore> searchAppStoreCategories(String q, Optional<TwitterOSType> osType) throws TwitterException {
List<HttpParameter> params = new ArrayList<>();
if (TwitterAdUtil.isNotNullOrEmpty(q)) {
params.add(new HttpParameter(PARAM_Q, q));
}
if (osType != null && osType.isPresent()) {
params.add(new HttpParameter(PARAM_OS_TYPE, osType.get().name()));
}
final String baseUrl = twitterAdsClient.getBaseAdsAPIUrl() + PATH_TARGETING_CRITERIA_APP_STORE_CATEGORIES;
final HttpResponse httpResponse = twitterAdsClient.getRequest(baseUrl, params.toArray(new HttpParameter[params.size()]));
try {
final Type type = new TypeToken<BaseAdsListResponse<TwitterAppStore>>() {
}.getType();
final BaseAdsListResponse<TwitterAppStore> baseAdsListResponse =
constructBaseAdsListResponse(httpResponse, httpResponse.asString(), type);
return baseAdsListResponse == null ? Collections.<TwitterAppStore>emptyList() : baseAdsListResponse.getData();
} catch (IOException e) {
throw new TwitterException("Failed to parse response for app store categories");
}
}
private static String generateFunctionName(Function function) {
Class<? extends Function> functionClass = function.getClass();
if (functionClass.isAnonymousClass()) {
// getSimpleName returns an empty String for anonymous classes
Type[] interfaces = functionClass.getInterfaces();
if (interfaces.length == 0) {
// extends an existing class (like RichMapFunction)
Class<?> functionSuperClass = functionClass.getSuperclass();
return functionSuperClass.getSimpleName() + functionClass.getName().substring(functionClass.getEnclosingClass().getName().length());
} else {
// implements a Function interface
Class<?> functionInterface = functionClass.getInterfaces()[0];
return functionInterface.getSimpleName() + functionClass.getName().substring(functionClass.getEnclosingClass().getName().length());
}
} else {
return functionClass.getSimpleName();
}
}
/**
* This will give you the request body nicely parsed. You can register your
* own parsers depending on the request type.
* <p>
*
* @param classOfT The class of the result.
* @return The parsed request or null if something went wrong.
*/
@Override
public <T> T body(Class<T> classOfT, Type genericType) {
String rawContentType = request().contentType();
// If the Content-type: xxx header is not set we return null.
// we cannot parse that request.
if (rawContentType == null) {
return null;
}
// If Content-type is application/json; charset=utf-8 we split away the charset
// application/json
String contentTypeOnly = HttpUtils.getContentTypeFromContentTypeAndCharacterSetting(
rawContentType);
BodyParser parser = services.getContentEngines().getBodyParserEngineForContentType(contentTypeOnly);
if (parser == null) {
return null;
}
return parser.invoke(this, classOfT, genericType);
}
public static String serialize(boolean escapeUnicode, Type type, Object obj) {
JsonStream stream = JsonStreamPool.borrowJsonStream();
try {
stream.reset(null);
stream.writeVal(type, obj);
if (escapeUnicode) {
return new String(stream.buf, 0, stream.count);
} else {
return new String(stream.buf, 0, stream.count, "UTF8");
}
} catch (IOException e) {
throw new JsonException(e);
} finally {
JsonStreamPool.returnJsonStream(stream);
}
}
@Override
public Object readArray(Type target) {
log.debug("readArray - target: {}", target);
Object result = null;
int count = buf.getInt();
log.debug("Count: {}", count);
// To conform to the Input API, we should convert the output into an Array if the Type asks us to.
Class<?> collection = Collection.class;
if (target instanceof Class<?>) {
collection = (Class<?>) target;
}
List<Object> resultCollection = new ArrayList<>(count);
if (collection.isArray()) {
result = ArrayUtils.getArray(collection.getComponentType(), count);
} else {
result = resultCollection;
}
storeReference(result); // reference should be stored before reading of objects to get correct refIds
for (int i = 0; i < count; i++) {
resultCollection.add(Deserializer.deserialize(this, Object.class));
}
if (collection.isArray()) {
ArrayUtils.fillArray(collection.getComponentType(), result, resultCollection);
}
return result;
}
private String printBounds(String name, Type[] bounds, boolean lower) {
StringBuilder builder=new StringBuilder();
builder.append(name);
if(bounds.length>0) {
String prefix = lower?"super":"extends";
builder.append(" ").append(prefix).append(" ");
for(int i=0;i<bounds.length;i++) {
if(i>0) {
builder.append(" & ");
}
Type bound = bounds[i];
builder.append(toString(bound,false));
}
}
return builder.toString();
}
/**
*代理商可查询自己及名下代客所有业务明细
* @param req DescribeAgentBillsRequest
* @return DescribeAgentBillsResponse
* @throws TencentCloudSDKException
*/
public DescribeAgentBillsResponse DescribeAgentBills(DescribeAgentBillsRequest req) throws TencentCloudSDKException{
JsonResponseModel<DescribeAgentBillsResponse> rsp = null;
try {
Type type = new TypeToken<JsonResponseModel<DescribeAgentBillsResponse>>() {
}.getType();
rsp = gson.fromJson(this.internalRequest(req, "DescribeAgentBills"), type);
} catch (JsonSyntaxException e) {
throw new TencentCloudSDKException(e.getMessage());
}
return rsp.response;
}
public TypeBinaryExpression(ExpressionType nodeType, Expression expression,
Type type) {
super(nodeType, Boolean.TYPE);
assert expression != null : "expression should not be null";
this.expression = expression;
this.type = type;
}
public void testOurTypeFunctionality() throws Exception {
Type parameterizedType = new TypeToken<List<String>>() {}.getType();
Type genericArrayType = new TypeToken<List<String>[]>() {}.getType();
assertEquals(parameterizedType, ourType.getGenericComponentType());
assertEquals(genericArrayType, ourType);
assertEquals(genericArrayType.hashCode(), ourType.hashCode());
}
private Map<String, Type> resolveTypeVariables(Class<?> clazz) {
ImmutableMap.Builder<String, Type> result = ImmutableMap.builder();
for (TypeVariable<? extends Class<?>> typeParameter : clazz.getTypeParameters()) {
result.put(typeParameter.getName(), getOnlyBound(typeParameter));
}
return result.build();
}
/**
* Returns a type that represents an unknown supertype of {@code bound}. For
* example, if {@code bound} is {@code String.class}, this returns {@code ?
* super String}.
*/
public static WildcardType supertypeOf(Type bound) {
Type[] lowerBounds;
if (bound instanceof WildcardType) {
lowerBounds = ((WildcardType) bound).getLowerBounds();
} else {
lowerBounds = new Type[] { bound };
}
return new WildcardTypeImpl(new Type[] { Object.class }, lowerBounds);
}
/**
* List all externalDatabaseServers (asynchronously)
*
* @param environment (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call listAsync(String environment, final ApiCallback<List<String>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = listValidateBeforeCall(environment, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<String>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
public static Class getGenericType(Field field) {
Class type = field.getType();
if (!Collection.class.isAssignableFrom(type) && !Map.class.isAssignableFrom(type)) {
throw new IllegalArgumentException(String.format("only Collection and Map can get generic type at runtime, field[name:%s] is %s",
field.getName(), type.getName()));
}
try {
Type gtype = field.getGenericType();
if (!(gtype instanceof ParameterizedType)) {
return null;
}
Type[] gtypes = ((ParameterizedType)gtype).getActualTypeArguments();
if (gtypes.length == 0) {
return null;
}
Type ret = null;
if (Collection.class.isAssignableFrom(type)) {
ret = gtypes[0];
} else {
ret = gtypes[1];
}
if (ret instanceof Class) {
return (Class) ret;
} else {
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*读取或修改DDoS的防护等级
* @param req ModifyDDoSLevelRequest
* @return ModifyDDoSLevelResponse
* @throws TencentCloudSDKException
*/
public ModifyDDoSLevelResponse ModifyDDoSLevel(ModifyDDoSLevelRequest req) throws TencentCloudSDKException{
JsonResponseModel<ModifyDDoSLevelResponse> rsp = null;
try {
Type type = new TypeToken<JsonResponseModel<ModifyDDoSLevelResponse>>() {
}.getType();
rsp = gson.fromJson(this.internalRequest(req, "ModifyDDoSLevel"), type);
} catch (JsonSyntaxException e) {
throw new TencentCloudSDKException(e.getMessage());
}
return rsp.response;
}
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
JavaType targetType =
genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(),
parameter.getRequired());
}
/**
* <p> Return a map of the type arguments of a class in the context of <code>toClass</code>. </p>
*
* @param cls the class in question
* @param toClass the context class
* @param subtypeVarAssigns a map with type variables
* @return the map with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, Class<?> toClass,
Map<TypeVariable<?>, Type> subtypeVarAssigns) {
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
// can't work with primitives
if (cls.isPrimitive()) {
// both classes are primitives?
if (toClass.isPrimitive()) {
// dealing with widening here. No type arguments to be
// harvested with these two types.
return new HashMap<TypeVariable<?>, Type>();
}
// work with wrapper the wrapper class instead of the primitive
cls = ClassUtils.primitiveToWrapper(cls);
}
// create a copy of the incoming map, or an empty one if it's null
HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>()
: new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);
// has target class been reached?
if (toClass.equals(cls)) {
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
}
/**
*查询实例访问命令
* @param req DescribeInstanceMonitorTopNCmdRequest
* @return DescribeInstanceMonitorTopNCmdResponse
* @throws TencentCloudSDKException
*/
public DescribeInstanceMonitorTopNCmdResponse DescribeInstanceMonitorTopNCmd(DescribeInstanceMonitorTopNCmdRequest req) throws TencentCloudSDKException{
JsonResponseModel<DescribeInstanceMonitorTopNCmdResponse> rsp = null;
try {
Type type = new TypeToken<JsonResponseModel<DescribeInstanceMonitorTopNCmdResponse>>() {
}.getType();
rsp = gson.fromJson(this.internalRequest(req, "DescribeInstanceMonitorTopNCmd"), type);
} catch (JsonSyntaxException e) {
throw new TencentCloudSDKException(e.getMessage());
}
return rsp.response;
}
@Override
public <T> ListenableFuture<ResponseEntity<T>> exchange(String url, HttpMethod method,
@Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType,
Object... uriVariables) throws RestClientException {
Type type = responseType.getType();
AsyncRequestCallback requestCallback = httpEntityCallback(requestEntity, type);
ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
return execute(url, method, requestCallback, responseExtractor, uriVariables);
}
/**
** 对媒体禁播后,除了点播控制台预览,其他场景访问视频各种资源的 URL(原始文件、转码输出文件、截图等)均会返回 403。
禁播/解禁操作全网生效时间约 5~10 分钟。
* @param req ForbidMediaDistributionRequest
* @return ForbidMediaDistributionResponse
* @throws TencentCloudSDKException
*/
public ForbidMediaDistributionResponse ForbidMediaDistribution(ForbidMediaDistributionRequest req) throws TencentCloudSDKException{
JsonResponseModel<ForbidMediaDistributionResponse> rsp = null;
try {
Type type = new TypeToken<JsonResponseModel<ForbidMediaDistributionResponse>>() {
}.getType();
rsp = gson.fromJson(this.internalRequest(req, "ForbidMediaDistribution"), type);
} catch (JsonSyntaxException e) {
throw new TencentCloudSDKException(e.getMessage());
}
return rsp.response;
}
@Override
public BaseAdsListResponseIterable<PromotableUser> getPromotableUsers(String accountId, boolean withDeleted) throws TwitterException {
TwitterAdUtil.ensureNotNull(accountId, "accountId");
final List<HttpParameter> params = new ArrayList<>();
params.add(new HttpParameter(PARAM_WITH_DELETED, withDeleted));
final String baseUrl = twitterAdsClient.getBaseAdsAPIUrl() + PREFIX_ACCOUNTS_URI + accountId + PATH_PROMOTABLE_USERS;
final Type type = new TypeToken<BaseAdsListResponse<PromotableUser>>() {
}.getType();
return twitterAdsClient.executeHttpListRequest(baseUrl, params, type);
}
@Override
public T readFrom(final Class<T> type, final Type genericType, final Annotation[] annotations,
final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream)
throws IOException, WebApplicationException {
final MessageBodyReader<T> reader = readers.get(mediaTypeWithoutParams(mediaType));
if (reader != null) {
return reader.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
} else {
throw new InternalServerErrorException("unsupported media type");
}
}
/**
*删除该人员库及包含的所有的人员。同时,人员对应的所有人脸信息将被删除。若某人员同时存在多个人员库中,该人员不会被删除,但属于该人员库中的自定义描述字段信息会被删除,属于其他人员库的自定义描述字段信息不受影响。
* @param req DeleteGroupRequest
* @return DeleteGroupResponse
* @throws TencentCloudSDKException
*/
public DeleteGroupResponse DeleteGroup(DeleteGroupRequest req) throws TencentCloudSDKException{
JsonResponseModel<DeleteGroupResponse> rsp = null;
try {
Type type = new TypeToken<JsonResponseModel<DeleteGroupResponse>>() {
}.getType();
rsp = gson.fromJson(this.internalRequest(req, "DeleteGroup"), type);
} catch (JsonSyntaxException e) {
throw new TencentCloudSDKException(e.getMessage());
}
return rsp.response;
}
/**
*本接口(ModifyDBInstanceSpec)用于调整MongoDB云数据库实例配置。接口支持的售卖规格,可从查询云数据库的售卖规格(DescribeSpecInfo)获取。
* @param req ModifyDBInstanceSpecRequest
* @return ModifyDBInstanceSpecResponse
* @throws TencentCloudSDKException
*/
public ModifyDBInstanceSpecResponse ModifyDBInstanceSpec(ModifyDBInstanceSpecRequest req) throws TencentCloudSDKException{
JsonResponseModel<ModifyDBInstanceSpecResponse> rsp = null;
try {
Type type = new TypeToken<JsonResponseModel<ModifyDBInstanceSpecResponse>>() {
}.getType();
rsp = gson.fromJson(this.internalRequest(req, "ModifyDBInstanceSpec"), type);
} catch (JsonSyntaxException e) {
throw new TencentCloudSDKException(e.getMessage());
}
return rsp.response;
}
/**
* Resolves class by generic map if required(when type is TypeVariable).
*/
private Type resolveGenericType( Type type, Map<String, Type> genericsInfo ) {
if ( type instanceof TypeVariable ) {
String name = ( (TypeVariable<?>) type ).getName();
type = genericsInfo.get( name );
if ( type == null ) {
throw new RuntimeException( "Unknown generics for '" + name + "'" );
}
}
return type;
}