java_lang_reflect_Constructor.cc revision 7940e44f4517de5e2634a7e07d58d0fb26160513
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "class_linker.h"
18#include "jni_internal.h"
19#include "mirror/class-inl.h"
20#include "mirror/abstract_method.h"
21#include "mirror/abstract_method-inl.h"
22#include "mirror/object-inl.h"
23#include "object_utils.h"
24#include "reflection.h"
25#include "scoped_thread_state_change.h"
26
27namespace art {
28
29/*
30 * We get here through Constructor.newInstance().  The Constructor object
31 * would not be available if the constructor weren't public (per the
32 * definition of Class.getConstructor), so we can skip the method access
33 * check.  We can also safely assume the constructor isn't associated
34 * with an interface, array, or primitive class.
35 */
36static jobject Constructor_newInstance(JNIEnv* env, jobject javaMethod, jobjectArray javaArgs) {
37  ScopedObjectAccess soa(env);
38  mirror::AbstractMethod* m = soa.Decode<mirror::Object*>(javaMethod)->AsMethod();
39  mirror::Class* c = m->GetDeclaringClass();
40  if (UNLIKELY(c->IsAbstract())) {
41    ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow();
42    soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/InstantiationException;",
43                                   "Can't instantiate %s %s",
44                                   c->IsInterface() ? "interface" : "abstract class",
45                                   PrettyDescriptor(c).c_str());
46    return NULL;
47  }
48
49  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(c, true, true)) {
50    DCHECK(soa.Self()->IsExceptionPending());
51    return NULL;
52  }
53
54  mirror::Object* receiver = c->AllocObject(soa.Self());
55  if (receiver == NULL) {
56    return NULL;
57  }
58
59  jobject javaReceiver = soa.AddLocalReference<jobject>(receiver);
60  InvokeMethod(soa, javaMethod, javaReceiver, javaArgs);
61
62  // Constructors are ()V methods, so we shouldn't touch the result of InvokeMethod.
63  return javaReceiver;
64}
65
66static JNINativeMethod gMethods[] = {
67  NATIVE_METHOD(Constructor, newInstance, "([Ljava/lang/Object;)Ljava/lang/Object;"),
68};
69
70void register_java_lang_reflect_Constructor(JNIEnv* env) {
71  REGISTER_NATIVE_METHODS("java/lang/reflect/Constructor");
72}
73
74}  // namespace art
75