对于想了解如何优雅的使用Objects.requireNonNull(Tobj,Stringmessage)定制你的NPE异常的读者,本文将是一篇不可错过的文章,并且为您提供关于#-net-canno
对于想了解如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常的读者,本文将是一篇不可错过的文章,并且为您提供关于# - net - cannot access a disposed object r nobject name filebufferingreadstream、@Nonnull和Objects.requireNonNull有什么区别、avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么、c# – 无法将System.Data.Entity.Core.Objects.ObjectResult类型隐式转换为System.Data.Objects.ObjectResult的有价值信息。
本文目录一览:- 如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常
- # - net - cannot access a disposed object r nobject name filebufferingreadstream
- @Nonnull和Objects.requireNonNull有什么区别
- avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么
- c# – 无法将System.Data.Entity.Core.Objects.ObjectResult类型隐式转换为System.Data.Objects.ObjectResult
如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常
IDEA中习惯跟踪源码实现逻辑,多次碰到Objects.requireNonNull(T obj)这个方法,改方法主要用于提早判断对象是否为空,以便更早的抛出NPE
平时小组开发中强调程序健壮性,不允许组员的代码中出现明显的NPE,这样多数时候都要写判空逻辑,抛出自定义的异常
我们看下具体的源码:
/**
* Checks that the specified object reference is not {@code null}.
* This method is designed primarily for doing parameter validation in methods
* and constructors, as demonstrated below:
* <blockquote><pre>
* public Foo(Bar bar) {
* this.bar = Objects.requireNonNull(bar);
* }
* </pre></blockquote>
*
* @param obj the object reference to check for nullity
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
*/
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
解释:检查定义的对象引用不为空。设计该方法主要用来做方法和构造函数中的参数校验
如上,如果直接使用仍然是抛出一个NPE,除了能提早检测和抛出异常,无法直接在业务中使用
继续往下滚动,发现还有这个方法
/**
* Checks that the specified object reference is not {@code null} and
* throws a customized {@link NullPointerException} if it is. This method
* is designed primarily for doing parameter validation in methods and
* constructors with multiple parameters, as demonstrated below:
* <blockquote><pre>
* public Foo(Bar bar, Baz baz) {
* this.bar = Objects.requireNonNull(bar, "bar must not be null");
* this.baz = Objects.requireNonNull(baz, "baz must not be null");
* }
* </pre></blockquote>
*
* @param obj the object reference to check for nullity
* @param message detail message to be used in the event that a {@code
* NullPointerException} is thrown
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
*/
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}
and throws a customized {@link NullPointerException} if it is:定制的空指针异常
and constructors with multiple parameters :多参数的构造函数
这样,下次我们想抛出一个自定义的空指针异常的时候,以前是:
if(obj==null){
throw new xxxException("该记录不存在xxxx");
}
现在可以更优雅的写Objects.requireNonNull(T obj,"该记录不存在xxxx")
代码实现区别不大,那么为啥不选择优雅^_^
# - net - cannot access a disposed object r nobject name filebufferingreadstream
.Net Core 2.1-Cannot access a disposed object.Object name: ''IServiceProvider'' (3)
I just migrated .NET Core 2.0 to .NET Core 2.1. Everything went fine, but when I try to login now I get the folowing error:
- $exception {System.ObjectDisposedException: Cannot access a disposed object. Object name: ''IServiceProvider''.
This happens in this bit of code:
public class AppContractResolver : DefaultContractResolver { private readonly IServiceProvider _services; public AppContractResolver(IServiceProvider services) { _services = services; } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { var httpContextAccessor = _services.GetService<IHttpContextAccessor>(); var user = httpContextAccessor.HttpContext.User; List<JsonProperty> properies = base.CreateProperties(type, memberSerialization).ToList(); properies = FilterOneClaimGranted(type, properies, user); return properies; }
It happens on this line:
var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
This did work on .NET Core 2.0
I have tried adding the HttpContextAccessor
to my startup, but that did not work.
So, how do I fix this?
Let me know if you need more code. I will happily provide more, but I don''t know what you might or might not need, so therefor I did not add a lot of code.''
EDIT
I have added services.AddHttpContextAccessor();
to my startup, but that does not seem to work. Still getting the error.
EDIT 2:
Full stacktrace:
- $exception {System.ObjectDisposedException: Cannot access a disposed object. Object name: ''IServiceProvider''. at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException() at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at WebAPI.Extensions.AppContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization) in C:\Users\luukw\Desktop\stage\blacky-api\Blacky\Extensions\Resolver\AppContractResolver.cs:line 25 at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType) at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe(Type type) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)} System.ObjectDisposedException
For me it works with:
public void ConfigureServices(IServiceCollection services) { … services.AddHttpContextAccessor(); … }
and then:
public void Configure(IApplicationBuilder app, IHttpContextAccessor accessor) { ... ...accessor.HttpContext.RequestService ... }
I would imagine that the IServiceProvider
implementation may have been used in a using
statement inadvertently somewhere or been disposed outright.
To test if this is the case you could try to resolve the IHttpContextAccessor
right after, or in, the ConfigureServices
method.
If it resolves there you would need to step through to find out where the IServiceProvider
is being disposed.
In my case issue was in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services) { var svc = services.GetService<IServiceProvider>(); // <-- exception here }
just replace services.GetService<>()
with app.ApplicationServices.GetService<>()
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var svc = app.ApplicationServices.GetService<IServiceProvider>(); // no exception }
hope it helps
@Nonnull和Objects.requireNonNull有什么区别
以下两个代码段之间有什么区别?
public Integer getId(@Nonnull SomeObject obj){
// do some stuff
return id;
}
public Integer getId(SomeObject obj){
Objects.requireNonNull(SomeObject,"SomeObject is null");
// do some stuff
return id;
}
它们之间有什么显着差异。在这些情况下进行空值检查的正确方法是什么。
avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么
@蝙蝠 你好,想请教个问题:在 avro-rpc 中,如果协议是下面这样子:
{ "namespace": "com.acme", "protocol": "HelloWorld", "doc": "Protocol Greetings", "types": [ {"name": "Greeting", "type": "record", "fields": [ {"name": "message", "type": "string"}]}, {"name": "Curse", "type": "error", "fields": [ {"name": "message", "type": "string"}]} ], "messages": { "hello": { "doc": "Say hello.", "request": [{"name": "greeting", "type": "Greeting" }], "response": "Greeting", "errors": ["Curse"] } } }那么在
public Object GenericRequest.request(String messageName, Object request) throws IOException中间 request 应该传什么样的值呢,是 GenericRecord 类型的还是怎样?本质上想问的是,这里的 request 和协议中定义的 "request" 的 schema 之间的关系是怎么样的?
c# – 无法将System.Data.Entity.Core.Objects.ObjectResult类型隐式转换为System.Data.Objects.ObjectResult
无法隐式转换类型System.Data.Entity.Core.Objects.ObjectResult< X>到System.Data.Objects.ObjectResult< X>
我正在使用Visual Studio 2012.
解决方法
我终于意识到键盘和椅子之间存在问题.存储过程完成了选择,但我试图:
MyStoredProc_Result r = dbcontext.MyStoredPoc();
代替
MyStoredProc_Result r = dbcontext.MyStoredPoc().FirstOrDefault();
今天的关于如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常的分享已经结束,谢谢您的关注,如果想了解更多关于# - net - cannot access a disposed object r nobject name filebufferingreadstream、@Nonnull和Objects.requireNonNull有什么区别、avro-rpc 中协议定义的 request 的模式与 GenericRequest.request (String messageName, Object request) 中的 request 是一致对应的关系么、c# – 无法将System.Data.Entity.Core.Objects.ObjectResult类型隐式转换为System.Data.Objects.ObjectResult的相关知识,请在本站进行查询。
本文标签: